Block scoping in Python
Python uses function-level scoping, for most cases:
def f():
x = 6
if x > 0:
y = 5
print(y) # This works, even though `y` was declared inside the `if`
A variable declared anywhere outside a function is in the (module's) global scope, and a variable declared inside a function is in that function's scope except exceptions in except
blocks since it would create GC cycles and comprehension expressions because those behave like functions ; blocks like conditionals and loops don't have their own scope like in C-family languages such as C, C++, Java, etc.
JavaScript, famously, also historically used function scoping, with var
, though block scoping has been introduced in ES6 with the keywords let
and const
. Python doesn't have declarations though, so there's no real way to properly retrofit that onto the language, so we're still stuck with function scoping. Whether it's a good feature or not is outside the scope (got it?) of this blogpost.
Python's scoping is quite coherent with the absence of declarations, how would you do something like this:
if cond:
x = 5
else:
x = 6
If variables had to be declared, you'd have to resort to tricks like writing x = None
beforehand, but this messes