2

I can't help but wonder...

Config:

mathieu@mathieu-UX21E:~/$ python --version
Python 2.7.5+

Code:

import logging
logger = logging.getLogger('x')

def main():
    print logger
    logger = 2

if __name__ == "__main__":
    main()

Output:

mathieu@mathieu-UX21E:~/$ python ./manager.py 
Traceback (most recent call last):
  File "./manager.py", line 9, in <module>
    main()
 File "./manager.py", line 5, in main
    print logger
UnboundLocalError: local variable 'logger' referenced before assignment

Obviously, I would expect that print statement to access the globally-defined logger variable. Is there something I did not understand about the python variable scoping rules ?

Also, obviously, the logger = 2 statement should not do much. However, if I remove it, the undefined variable exception disapears.

mathieu
  • 2,954
  • 2
  • 20
  • 31
  • You are assigning to the name => a local. – Martijn Pieters Feb 14 '14 at 13:29
  • 1
    "Is there something I did not understand about the python variable scoping rules ?" Yes. You don't understand that you can have local variables that have the same name as variables declared at global scope. If you want to use the variable at global scope, you need to say so: `def main(): global logging; print logger; logger = 2` – hughdbrown Feb 14 '14 at 13:43
  • That should be `global logger`. Sorry. – hughdbrown Feb 14 '14 at 14:18

1 Answers1

1

As long as you don't redefine a name (that is, assign it to another value), you can use it without implicitly getting it from the global scope with the global statement.

Once you want to redefine it or modify it in anyway, you need to be explicit about which name you are talking about.

>>> a = 'hello'
>>> def f():
...    print(a)
... 
>>> def f2():
...    global a
...    a = 'world'
...    print(a)
... 
>>> f()
hello
>>> f2()
world
>>> a
'world'
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284