473,406 Members | 2,843 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

UnboundLocalError on shadowed import

I was going to file this as a bug in the tracker, but maybe it's not really
a bug. Poor Python code does what I consider to be unexpected. What's your
opinion?

With Python 2.3.2 (but also happens with 2.2)

An import within a function that shadows a global import can raise
UnboundLocalError. I think the real problem is that the the local 'import
sys' is seen as occuring after the use of sys within this function, even
though sys is imported in global scope.

import sys

def t():
sys.exit(0)
import sys
sys.exit(1)

if __name__ == "__main__":
t()

I noticed this when editing an existing module. After adding 'import sys' at
the global level and then using sys in the function (and not noticing that
this function imported sys locally below), I got the UnboundLocalError

python2.3 ~/temp/test.py
Traceback (most recent call last):
File "/home/bkc/temp/test.py", line 10, in ?
t()
File "/home/bkc/temp/test.py", line 4, in t
sys.exit(0)
UnboundLocalError: local variable 'sys' referenced before assignment

This is not much of an error. The local import is superfluous, and no one
would really write code this way. But should it raise an exception?

--
Novell DeveloperNet Sysop #5

_


Jul 18 '05 #1
3 2578
Brad Clements wrote:
python2.3 ~/temp/test.py
Traceback (most recent call last):
File "/home/bkc/temp/test.py", line 10, in ?
t()
File "/home/bkc/temp/test.py", line 4, in t
sys.exit(0)
UnboundLocalError: local variable 'sys' referenced before assignment

This is not much of an error. The local import is superfluous, and no one
would really write code this way. But should it raise an exception?


It "has to" raise an exception. The use of "sys" inside the function
is local (because you assign to it, because "import sys" is effectively
an assignment). Locals are not handled quite the same as other names,
as you know -- they are turned into index lookups in a list instead of
hash lookups in a dictionary. The interpreter can't know that your use
of sys.exit(0) is supposed to refer to the global sys, because all uses
of "sys" are really just "local variable number 3" or something like
that inside the function.

Basically, "don't do that" is about the best you'll get, I think.

-Peter
Jul 18 '05 #2
Peter Hansen wrote:
It "has to" raise an exception. The use of "sys" inside the function
is local (because you assign to it, because "import sys" is effectively
an assignment). Locals are not handled quite the same as other names,
as you know -- they are turned into index lookups in a list instead of
hash lookups in a dictionary. The interpreter can't know that your use
of sys.exit(0) is supposed to refer to the global sys, because all uses
of "sys" are really just "local variable number 3" or something like
that inside the function.

Basically, "don't do that" is about the best you'll get, I think.


Well, just for the sake of it, there still is the obvious option of
adding the line "global sys" before sys.exit(0) to tell the interpreter
to use the "globally imported sys".

--
Vincent Wehren
Jul 18 '05 #3
vincent wehren wrote:
Peter Hansen wrote:
It "has to" raise an exception. The use of "sys" inside the function
is local (because you assign to it, because "import sys" is effectively
an assignment). Locals are not handled quite the same as other names,
as you know -- they are turned into index lookups in a list instead of
hash lookups in a dictionary. The interpreter can't know that your use
of sys.exit(0) is supposed to refer to the global sys, because all uses
of "sys" are really just "local variable number 3" or something like
that inside the function.

Basically, "don't do that" is about the best you'll get, I think.


Well, just for the sake of it, there still is the obvious option of
adding the line "global sys" before sys.exit(0) to tell the interpreter
to use the "globally imported sys".


Which basically amounts to "not doing that". ;-) You're right...
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Alex Gittens | last post by:
I'm trying to define a function that prints fields of given widths with specified alignments; to do so, I wrote some helper functions nested inside of the print function itself. I'm getting an...
8
by: David Bear | last post by:
I'm attempting to use the cgi module with code like this: import cgi fo = cgi.FieldStorage() # form field names are in the form if 'name:part' keys = fo.keys() for i in keys: try:...
15
by: Paddy | last post by:
Hi, I am trying to work out why I get UnboundLocalError when accessing an int from a function where the int is at the global scope, without explicitly declaring it as global but not when accessing...
2
by: Matthew Franz | last post by:
I'm probably fundamentally misunderstanding the way the interpreter works with regard to scope, but is this the intended behavior... franz-macbook:~ mdfranz$ python unboundlocal.py ('Darwin',...
2
by: Konstantinos Pachopoulos | last post by:
Hi, i have a problem, the source of which is probably the fact, that i have not understood how to declare global variables - I use the Jython compiler, but i think this is a Python issue... ...
0
by: Terry Reedy | last post by:
Mr SZ wrote: you need global ORIG_TYPE,ORIG_MSG because this otherwise marks them as local.
8
by: defn noob | last post by:
isPrime works when just calling a nbr but not when iterating on a list, why? adding x=1 makes it work though but why do I have to add it? Is there a cleaner way to do it? def isPrime(nbr):...
1
by: nongnaeja | last post by:
I don't know ,why it's error This my code from PIL import Image def ch_red(tmp): R = tmp G = tmp B = tmp
1
by: AmeL | last post by:
I am stuck at the a small code as the following: This is module main, the main entry of the application : from irc_log_mod import * from irc_chatter_mod import * from inspect import * from...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.