Python has never used braces to define code blocks, it relies on indentation instead; this is one of the defining features of the language. There's even a little cookie that CPython gives you to show how strongly they feel about this:
>>> from __future__ import braces
SyntaxError: not a chance
When I saw this little snippet posted to a forum (since deleted) I thought it cannot possibly work. But it does!
>>> def hi(): {
print('Hello')
}
>>> hi()
Hello
Why does this code work, when it appears to violate the language syntax?
The braces aren't defining a code block as they would in other languages - they're defining a set. The print function is being evaluated and its return value (None) is being placed in the set. Once the set is created it is immediately discarded since it isn't being assigned to anything.
There are a couple of Python syntax features that are being exploited here. First, Python allows a single-statement code block to come immediately after a :. Second, an expression is allowed to span multiple lines under certain circumstances.
This code wouldn't have worked if the body of the block were more than one line, or if an assignment or statement other than a function call were attempted.
Here's a redoing of the function to make it clearer what's happening:
>>> def hi2(): print(
{ print('Hello') }
)
>>> hi2()
Hello
{None}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With