3

I have the following function in Python that seems to be working:

def test(self):
    x = -1
    # why don't I need to initialize y = 0 here?
    if (x < 0):
        y = 23

    return y

But for this to work why don't I need to initialize variable y? I thought Python had block scope so how is this possible?

Zulu
  • 8,765
  • 9
  • 49
  • 56
letter Q
  • 14,735
  • 33
  • 79
  • 118

4 Answers4

6

This appears to be a simple misunderstanding about scope in Python. Conditional statements don't create a scope. The name y is in the local scope inside the function, because of this statement which is present in the syntax tree:

y = 23

This is determined at function definition time, when the function is parsed. The fact that the name y might be used whilst unbound at runtime is irrelevant.

Here's a simpler example highlighting the same issue:

>>> def foo():
...     return y
...     y = 23
... 
>>> def bar():
...     return y
... 
>>> foo.func_code.co_varnames
('y',)
>>> bar.func_code.co_varnames
()
>>> foo()
# UnboundLocalError: local variable 'y' referenced before assignment
>>> bar()
# NameError: global name 'y' is not defined
Community
  • 1
  • 1
wim
  • 338,267
  • 99
  • 616
  • 750
2

It seems that you misunderstood this part of Python's documentation:

A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition.
...
A scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block.

So in this case block is something completely different from visual blocks of your code. Thereby if, for, while statements doesn't have their own scopes. But it is worth noting that comprehensions and generator expressions are implemented using a function scope, so they have their own scopes.

godaygo
  • 2,215
  • 2
  • 16
  • 33
1

There is actually no block scope in python. Variables may be local (inside of a function) or global (same for the whole scope of the program).

Once you've defined the variable y inside the 'if' block its value is kept for this specific function until you specifically delete it using the 'del' command, or the function exits. From the moment y is defined in the function, it is a local variable of this function.

Brenner
  • 78
  • 8
0

As in What's the scope of a Python variable declared in an if statement?: "Python variables are scoped to the innermost function or module; control blocks like if and while blocks don't count."

Also useful: Short Description of the Scoping Rules?

Community
  • 1
  • 1
BrechtDeMan
  • 6,589
  • 4
  • 24
  • 25