Is This Strange Expression Valid Python Syntax?

0
0
Asked By MellowRidge42 On

Ignoring whether it can run successfully, is this expression grammatically valid Python? Try to determine the answer from Python's grammar before testing it in an interpreter. A bonus explanation of how the expression is parsed would be appreciated.

3 Answers

Answered By QuietHarbor19 On

The grammar permits constructs such as `()()` and `...()`. That only means the parser accepts them; it does not guarantee that evaluation will work. In effect, parts of the expression behave like calling an empty tuple and calling the Ellipsis object, both of which raise errors. Likewise, the Ellipsis object normally has no `_` attribute.

Answered By CopperLynx7 On

Yes, it is syntactically valid, although it cannot normally succeed at runtime. The first three dots form the `...` Ellipsis literal, and the fourth dot accesses an attribute named `_`, producing `...._`. The following parentheses are parsed as a function call, with the nested parentheses forming an empty tuple expression. The expression then performs another attribute access involving an Ellipsis call and finally calls the resulting object with no arguments.

Answered By AmberOrbit5 On

The syntax itself does not require the `_` attribute to exist. Attribute lookup and callability are runtime concerns, so a Python implementation could theoretically make the expression evaluate by allowing the Ellipsis type to have a callable `_` attribute and arranging for the intermediate results to be callable. That would be unusual implementation-specific behavior, but it does not change the fact that the original text is grammatically valid.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.