36

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)
Glide
  • 20,235
  • 26
  • 86
  • 135

3 Answers3

72

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.

agf
  • 171,228
  • 44
  • 289
  • 238
  • Oh... sorry.. I was wrong about that. – Owen Sep 12 '11 at 01:59
  • @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. – agf Sep 12 '11 at 02:23
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

Community
  • 1
  • 1
Remi
  • 20,619
  • 8
  • 57
  • 41
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.

Winston Ewert
  • 44,070
  • 10
  • 68
  • 83
  • 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 Sep 12 '11 at 02:16
  • @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. – detly Sep 12 '11 at 03:21
  • @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. – detly Sep 12 '11 at 03:23
  • @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 Ewert Sep 12 '11 at 03:25
  • @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. – agf Sep 12 '11 at 03:30
  • @agf, yes. That's why I edited. I didn't think of classes originally, because I don't typically think of those as variables. – Winston Ewert Sep 12 '11 at 03:42