Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, why is a bare function object valid code? [closed]

Tags:

python

Why is the following valid?

#!/usr/bin/python
def spam():
   pass

spam

I understand that functions are objects but I think code such as the above is never useful and always the result of a mistake. Why doesn't it result in an error on the line referencing the spam function object?

like image 565
Stuart Woodward Avatar asked Apr 11 '26 04:04

Stuart Woodward


1 Answers

Every expression is a valid statement. Using a local variable (no matter what it refers to) is a valid expression. Due to late binding and dynamicness, you can't detect at compile time whether it refers to a function or something else (though in this case you don't need to know that, as just referencing a local never does anything). A runtime check would be quite expensive for no gain.

That leaves prohibiting statements of the form <local variable>;. Prohibiting this case specifically is inconsistent, takes extra work, and does not help much IMHO. I don't see a technical reason it couldn't be done, so it probably boils down to the BDFL not wanting a special case for this.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!