serhii.net

In the middle of the desert you can say anything you want

23 Nov 2021

211123-2333 python scopes

(From a python riddle at work)

Things declared in if __name__ == '__main__' are in global scope. Not because it’s special, but because ..global scope. All these bugs go away if you move main() to a separate function.

Code from SO answer:[^2]

In main:

>>> if __name__ == '__main__':
...     x = 1
... print 'x' in globals()
True

Inside a function:

>>> def foo():
...     if __name__ == '__main__':
...         bar = 1
... foo()
... print 'bar' in globals()
False

Python doesn’t have block-local scope, so any variables you use inside an if block will be added to the closest enclosing “real” scope.

Someone mentioned that if __name__ == '__main__' can happen anywhere in the code. Never thought about this

Nel mezzo del deserto posso dire tutto quello che voglio.