[Tutor] variable existence q

Peter Otten __peter__ at web.de
Sat Aug 15 23:11:36 CEST 2015


Clayton Kirkwood wrote:

> 10 top_directory = "/users/Clayton/Pictures"
> 
>     def override_defaults():
> 56     return( top_directory, filetypes, target_directory )
>      
> 80 top_directory, filetypes, target_directory = override_defaults()
> 
> 
>   File "C:/Users/Clayton/python/find picture duplicates/find picture
> duplicates", line 80, in <module>
>     top_directory, filetypes, target_directory = override_defaults()
>   File "C:/Users/Clayton/python/find picture duplicates/find picture
> duplicates", line 56, in override_defaults
>     return( top_directory, filetypes, target_directory )
> UnboundLocalError: local variable 'top_directory' referenced before
> assignment
> 
> I am facing the above error:
> 10 occurs first
> 80 then runs
> 56 appears to not work, the function logically does nothing
> I thought that variables in the main were visible to defined functions in
> the same file, as long as the assignment occurs physically before use.

I don't think it's relevant here, but generally speaking the order in the 
file doesn't matter, only the order of execution matters. For example

>>> def f(): return x
... 
>>> x = 42
>>> 
>>> print(f())
42

Even though the assignment to x occurs physically after the function 
definition, as the function is invoked after that assignment you don't get a 
NameError.

> When debugging, inside of override_defaults sees the correct value.
> What am I not seeing?

There must be an assignment to top_directory inside override_defaults().
This assignment turns top_directory into a local variable:

>>> def f():
...     if False: x = 42 # this turns x into a local name
...     return x
... 
>>> x = 42
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in f
UnboundLocalError: local variable 'x' referenced before assignment
>>> x # the global x is defined, but not visible inside the function
42

Wether a name is local to the function or global is determined statically by 
the compiler. This is different from class definitions. Compare:

>>> x = 42
>>> class A: x = x
... 
>>> A.x
42
>>> def f(): x = x
... 
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in f
UnboundLocalError: local variable 'x' referenced before assignment





More information about the Tutor mailing list