Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Python print a variable that is out of scope

Tags:

python

block

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?

like image 239
Wang-Zhao-Liu Q Avatar asked Jun 04 '26 00:06

Wang-Zhao-Liu Q


1 Answers

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
like image 67
wim Avatar answered Jun 06 '26 13:06

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!