On 15/08/2015 22:11, Peter Otten wrote:
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


Your explanation doesn't make any sense to me. I'd have thought that having assigned top_directory at line 10, but then trying to reassign it at line 80, means that the function now knows nothing about it, hence the error.

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to