37

In Python, are variable scopes inside if-statements visible outside of the if-statement? (coming from a Java background, so find this a bit odd)

In the following case, name is first defined inside the if-block but the variable is visible outside of the if-block as well. I was expecting an error to occur but 'joe' gets printed.

if 1==1:
    name = 'joe'
print(name)
0

3 Answers 3

73

if statements don't define a scope in Python.

Neither do loops, with statements, try / except, etc.

Only modules, functions and classes define scopes.

See Python Scopes and Namespaces in the Python Tutorial.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh... sorry.. I was wrong about that.
@Owen you're thinking of the nonlocal keyword I assume, which doesn't define a scope, just adds a syntax for referring to an enclosing but non-global scope.
2

Yes, in Python, variable scopes inside if-statements are visible outside of the if-statement. Two related questions gave an interestion discussion:

Short Description of the Scoping Rules?

and

Python variable scope error

Comments

1

All python variables used in a function live in the function level scope. (ignoring global and closure variables)

It is useful in case like this:

if foo.contains('bar'):
   value = 2 + foo.count('b')
else:
   value = 0

That way I don't have to declare the variable before the if statement.

6 Comments

Your first line is incorrect. If I define a variable in a class definition it's not in the global scope, a closure, or function level scope.
@agf - classes don't define a new scope — I can't access class variables from a method without qualification (ie. I need Class.thing or self.thing, not just thing). They have their own namespace, though.
@agf - actually, now that I think about it, I guess you can access class variables from the class definition outside of methods, so I'm not sure what that is.
@afg, stuff you create in a class definition is stored in the local scope just like when you are executing a function. That scope later becomes the class dictionary. But that's probably beyond the scope of this answer.
@Winston I understand that either is the local scope, but read the first line prior to the edit -- he specifically said "all [local] Python variables live in the function level scope". That's incorrect; there is another statement that defines a local scope other than a function definition -- a class definition.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.