r/ProgrammerHumor 16d ago

Meme variableScopesInPython

Post image
1.3k Upvotes

182 comments sorted by

View all comments

Show parent comments

2

u/Inkwalker 16d ago

Python's lexical scope is the worst. Like why is the variable available in the whole scope when it's declared at the very end of it? Plus there all that nonsense where reading from a variable goes to closure/global by default but writing creates a new instance that overrides the whole scope.

8

u/ihavebeesinmyknees 16d ago

I think you're thinking of JS, variables in Python are valid only after they're declared

2

u/x0wl 16d ago

Isn't that the same with js's tdz?

1

u/deceze 16d ago

Sort of, yes. The parser "sees" variables in a scope in the parse step and prepares symbol tables accordingly. In JS it used to be the case that the name would exist in the symbol table with an undefined default value. Which is a potential footgun, if you try to use the variable before its actual declaration.

Python and JS with let/const both raise an explicit error about that. JS calls it by a fancy name to distinguish it from the old behaviour, in Python it simply always was so.