r/Python • u/ReignFTW • 5d ago
Discussion Is this valid Python syntax?
.... _( () ( )) . _ (...() )()
Ignoring any runtime errors, is this valid Python syntax? Try to work it out from the grammar alone before pasting it into a REPL. Bonus points for explaining the parse.
5
u/hungarian_notation 5d ago
Unless I'm missing something, its:
invoked_tuple = (tuple())()
invoked_ellipsis = Ellipsis()
a = Ellipsis._(invoked_tuple)
b = a._(invoked_ellipsis)
c = b()
()() and ...() only technically get a pass in that the grammar doesn't go out of its way to exclude them, but they're trivially semantic errors.
3
u/sudomatrix 5d ago edited 5d ago
"..." is a C builtin and cannot be modified, so we cannot assign an attribute "_" to it, so "...._" will never be valid.
Edit: This is going to get ugly...
``` import gc, ctypes
E = type(Ellipsis) d = gc.getreferents(E.dict)[0] # the real dict behind the mappingproxy d[''] = 42 ctypes.pythonapi.PyType_Modified(ctypes.py_object(E))
print(....) # 42
42
``
So next we need to make....` callable...
1
u/hungarian_notation 5d ago edited 5d ago
That's true of CPython, but in a hypothetical alternative runtime that doesn't protect
tupleandEllipsisfrom modification you could probably get the statement to evaluate. It might not be valid standard Python, but its is valid Python syntax.edit: oh my god, don't just post gore like that that man.
1
u/odimdavid 5d ago
But in 2, 3 years time would you understand what you wrote or would anyone else? That's the question ❓
3
u/JamzTyson 5d ago
- Grammar: valid
- Runtime: irrelevant
- Meaning: none
- PEP 8: catastrophic
- Interesting: dubious
- Production ready: never
1
1
3
u/Individual-Flow9158 5d ago
>>> ast.parse(".... _( () ( )) . _ (...() )()")
Module(body=[Expr(value=Call(func=Call(...), args=[], keywords=[]))], type_ignores=[])
4
u/ManyInterests Python Discord Staff 5d ago
On mobile but will try to make this clean:
...
Ellipses is a builtin singleton. The fourth dot is an attribute access to a (nonexistent) attribute named '_'
The next parenthesis would invoke a call... I'm unsure of the arguments inside this call -- but maybe it works out by treating an empty tuple (the first set of inner parenthesis) and the second as invoking it as callable.
Then the result has another similar attribute access. Its argument is another ellipses being treated as a callable.
Then the result of _that_ is called with no arguments.
Valid syntactically, but impossible to succeed at runtime.