I'm new to Python, so this is probably a simple scoping question. The following code in a Python file (module) is confusing me slightly:
if __name__ == '__main__':
x = 1
print x
In other languages I've worked in, this code would throw an exception, as the x
variable is local to the if
statement and should not exist outside of it. But this code executes, and prints 1. Can anyone explain this behavior? Are all variables created in a module global/available to the entire module?
you're executing this code from command line therefore
if
conditions is true andx
is set. Compare:Yes, they're in the same "local scope", and actually code like this is common in Python:
Note that
x
isn't declared or initialized before the condition, like it would be in C or Java, for example.In other words, Python does not have block-level scopes. Be careful, though, with examples such as
which would clearly raise a
NameError
exception.Unlike languages such as C, a Python variable is in scope for the whole of the function (or class, or module) where it appears, not just in the innermost "block". It is as though you declared
int x
at the top of the function (or class, or module), except that in Python you don't have to declare variables.Note that the existence of the variable
x
is checked only at runtime -- that is, when you get to theprint x
statement. If__name__
didn't equal"__main__"
then you would get an exception:NameError: name 'x' is not defined
.Scope in python follows this order:
Search the local scope
Search the scope of any enclosing functions
Search the global scope
Search the built-ins
(source)
Notice that
if
and other looping/branching constructs are not listed - only classes, functions, and modules provide scope in Python, so anything declared in anif
block has the same scope as anything decleared outside the block. Variables aren't checked at compile time, which is why other languages throw an exception. In python, so long as the variable exists at the time you require it, no exception will be thrown.Yes. It is also true for
for
scope. But not functions of course.In your example: if the condition in the
if
statement is false,x
will not be defined though.Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like
if
andwhile
blocks don't count, so a variable assigned inside anif
is still scoped to a function, class, or module.(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and
for
clause targets are implicit assignment.)