Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
UnboundLocalError when accessing location.is_authorised() inside function
-
UnboundLocalError when accessing location.is_authorised() inside function
When I try:
import location def get_direction(): if location.is_authorized(): #do something
I get an UnboundLocalError: local variable 'location' referenced before assignment.
But the similar code works with other modules e.g:
import time def get_time_diff(): if time.time() > 1234: #do something
How can I get around the UnboundLocalError? Importing the location module inside the function works, but I don't want to have to import it within each function that uses location.
Maybe I'm missing something obvious so any suggestions are appreciated!
-
I can’t reproduce this. Have you tried restarting (i.e. force-quitting) Pythonista?
-
This sort of thing can happen when using threads or button actions that use scripts that have been imported, when you run ine sdript, then another so that globals and user modules get cleared...
You may want to post a complete example where this occurs.
-
If I'm understanding the error message correctly, this doesn't have anything to do with missing globals. If you try to access a global that doesn't exist, you get a
NameError
. AnUnboundLocalError
means that you're trying to access a local variable that is currently unassigned.Short explanation about Python locals - whether a variable in a function is local or global is determined statically at "compile time". If a variable is assigned to in the function, it is always local, even before the assignment. For example the following code will always produce an
UnboundLocalError
:var = "global" def fun(): print(var) # raises UnboundLocalError("local variable 'var' referenced before assignment") var = "local" # var is assigned to in the function, which makes it local - the global variable var is hidden fun()
My guess is that you're accidentally using
location
as a variable name later on in the function. Something like this:import location def get_direction(): if location.is_authorized(): location = location.get_location() # ... do stuff with the location ... else: print("Location access not allowed!")
Because you're assigning to
location
, every use oflocation
in the function looks up the local variablelocation
- when that happens before it is assigned, you get anUnboundLocalError
like the one you posted. The fix for this is to choose a different name for the local variable, so it doesn't conflict with any globals that you want to use. -
This post is deleted!