SH | Diensttagebuch

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

23 Nov 2021

211123-2333 python packaging and poetry

(From MO’s python riddle at work)

Things declared in if __name__ == '__main__' are in global scope. Not because it’s special, but because scope.

Code from SO answer:[^2]

In main:

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

Inside a function:

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

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.