python – Whats the scope of a variable initialized in an if statement?

python – Whats the scope of a variable initialized in an if statement?

Python variables are scoped to the innermost function, class, or module in which theyre assigned. Control blocks like if and while blocks dont count, so a variable assigned inside an if 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 cant stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.)

Yes, theyre in the same local scope, and actually code like this is common in Python:

if condition:
  x = something
else:
  x = something else

use(x)

Note that x isnt 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

if False:
    x = 3
print(x)

which would clearly raise a NameError exception.

python – Whats the scope of a variable initialized in an if statement?

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 an if block has the same scope as anything decleared outside the block. Variables arent 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.

Leave a Reply

Your email address will not be published.