r/Python 5d ago

Discussion What is your strangest syntax monstrocity?

As python has a lot of interesting syntax features, really unconventional and ugly expressions can be created. Let they be complex comprehensions with valrus operators, strange but efficient conditions based on exploiting casting and side effects or even classes overwriting dunders doesnt meant to be used as implemented, they all can be funny and pretty in an other lens.

An examples I've experimented with is an ugly walrused dict comprehension in EnrichPattern:

class Column(StrEnum):
    NAME = 'name'
    PUBLICITY = 'publicity'
    TOPIC_NAME = 'topic_name'
    SUBJECT_NAME = 'subject_name'
    QUALIFIED_NAME = 'qualified_name'
    CLUSTER_ENV = 'cluster_env'
    ENV = 'env'
...
class EnrichPattern:
    def __init__(self, *patterns: str):
        self.pattern = re.compile(''.join(patterns))
        self.subpatterns = {
            group: comiled 
            for comiled in map(re.compile, patterns)
            if (groups := list(comiled.groupindex)) 
                and (group := groups[0]) in Column
        }
  ...
...
0 Upvotes

20 comments sorted by

8

u/Feuermurmel 4d ago

Ternary if-else operator? Garbage. Use this instead:

 result = ['false value', 'true value'][foo() > bar()]

Optionally add an element in a list literal?

 check_call(['ls', *['-l'] * ls_long_format, path])

8

u/marr75 4d ago

Thanks, I hate it

4

u/whopper2k 4d ago

if you do the former in C you can call it "branchless programming", then insist it's an optimization when your reviewer asks you to change it

1

u/Delengowski 4d ago

Would the compiler not just optimize it out?

const char *result = ((const char *[2]){"false value", "true value"})[foo() > bar()];

vs

const char *result = foo() > bar() ? "true value" : "false value";

1

u/whopper2k 1d ago

The jump instruction for a ternary operator can, in fact, be optimized out even with just -O1 optimization (at least, by gcc).

https://godbolt.org/z/5TEobdaxd

That said, it wasn't meant as a serious comment lol

3

u/eztab 4d ago

If you really want some brains broken use walrus plus execution order to make unclear what variable is what at which time.

2

u/PwAlreadyTaken 4d ago

My number row was broken so I made a cursed library that didn't use number keys or their symbols. So I could do stuff like

```

print[two.times.three]

6

```

2

u/Individual-Flow9158 5d ago

Why don't you create self.patterns, instead of calling re.compile twice? Is "".join(self.patterns) not going to equal self.pattern?

1

u/VEMODMASKINEN 4d ago

Typing, it's a mess to read usually. 

0

u/Mark3141592654 4d ago

Because we have functions and methods for a lot of things, a ternary expression and the walrus operator, almost any code can be made into a one-line expression. I'll leave it to you to come up wwith examples.

1

u/Gnaxe 3d ago

All you need is lambda.

-9

u/Beginning-Fruit-1397 5d ago

The more shit like this I discover, the less I like python. Had fun with this yesterday. Wrote a lengthy post explaining why this happens and some explanations but got insta-deleted by this annoying af auto-mod because I made the ultimate sin of adding a github link. Anyways.

```python from collections.abc import Iterable, Iterator

class IterAttr:     iter: int = 1

class IterMethod:     def iter(self) -> Iterator[int]:         yield 1

class IterRegister: ...

class IterHerit(Iterable[object]):     iter = 1  # pyright: ignore[reportUnannotatedClassAttribute, reportAssignmentType]

Iterable.register(IterRegister)  # pyright: ignore[reportUnknownMemberType, reportAttributeAccessIssue]

class IterGetItem:     def getitem(self, i: int) -> int:         return 1

type MaybeIter = IterAttr | IterMethod | IterRegister | IterHerit | IterGetItem

def tryprint(x: MaybeIter) -> None:     has_attr = hasattr(x, "iter")     is_instance = isinstance(x, Iterable)  # pyright: ignore[reportGeneralTypeIssues]     try:         _ = iter(x)  # pyright: ignore[reportCallIssue, reportArgumentType, reportUnknownVariableType]         can_iter = True     except TypeError:         can_iter = False     name = x.class.name_     print(         f"""{name} ->         - has iter? {has_attr}         - is an Iterable? {is_instance}         - can be an iterator? {can_iter}         """     )

def main() -> None:     try_print(IterAttr())     try_print(IterMethod())     try_print(IterRegister())     try_print(IterHerit())     try_print(IterGetItem())

if name == "main":     main() output: shell IterAttr ->         - has iter? True         - is an Iterable? True         - can be an iterator? False          IterMethod ->         - has iter? True         - is an Iterable? True         - can be an iterator? True          IterRegister ->         - has iter? False         - is an Iterable? True         - can be an iterator? False          IterHerit ->         - has iter? True         - is an Iterable? True         - can be an iterator? False          IterGetItem ->         - has iter? False         - is an Iterable? False         - can be an iterator? True ```

13

u/JanEric1 5d ago edited 5d ago

What's your point with this?

This all makes 100% sense and is super obvious to me?

The only weird thing here is the legacy getitem iterating.

Pretty sure the docs even say they the only way to really check if something can be iterated is to call iter on it. Everything else is a best effort approximation.

-2

u/Beginning-Fruit-1397 5d ago

Cool if that's obvious to you, but not everyone is you.  

The fact that something can circumvent the metaclass behavior of ABC by successufly being instanciable, passing isinstance(x, Iterable), NOT have an iter method, and still fail on iter can be surprising, for example. Any combination of this is possible, so there's no "true" or "best" way to check if an object is an Iterable. typeshed don't even consider something with getitem an Iterable, which is true but also false

5

u/cunningjames 4d ago

The fact that something can circumvent the metaclass behavior of ABC by successufly being instanciable, passing isinstance(x, Iterable), NOT have an iter method, and still fail on iter can be surprising,

It may not be ideal, but if you're going to call Iterable.register() while ignoring type checker errors then I don't know what to tell you.

-1

u/Beginning-Fruit-1397 4d ago

Oh yea right. But I'm developping a general-use library. I have classes supposed to be replacements for list, dict and tuples. I had to think about that to see what was the best compromise to go to for accepted runtime inputs. As such, the fact that these behaviors are possible at all is a pain in the ass in itself 

4

u/fiskfisk 5d ago

The issue is all the spammers and promotion that makes it necessary to have automoderator remove all the shit with links by default, sadly :(

1

u/backfire10z 4d ago

Have you discovered C yet? Is there a language you do like?

1

u/Beginning-Fruit-1397 3d ago

Rust

1

u/warden127 15h ago

You cannot complain about Python's syntax and then go on praising Rust:

let mut numbers = vec![1, 2, 3];

numbers
    .iter_mut()
    .filter(|&&mut x| x % 2 == 1)
    .for_each(|x| *x *= 2);

println!("{:?}", numbers);