[Python-bugs-list] [ python-Bugs-615123 ] Reimporting modules inside functions/cla

noreply@sourceforge.net noreply@sourceforge.net
Thu, 26 Sep 2002 13:13:16 -0700


Bugs item #615123, was opened at 2002-09-26 20:44
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=615123&group_id=5470

Category: Python Interpreter Core
Group: Python 2.3
Status: Closed
Resolution: Invalid
Priority: 6
Submitted By: Jesús Cea Avión (jcea)
Assigned to: Guido van Rossum (gvanrossum)
Summary: Reimporting modules inside functions/cla

Initial Comment:
Python 2.2.1 here.

Suppose this source code:

import sys
def a() :
  print sys.path
  import sys

When you execute "a()", I get the following error:

UnboundLocalError: local variable 'sys' referenced
before assignment


----------------------------------------------------------------------

>Comment By: Jesús Cea Avión (jcea)
Date: 2002-09-26 22:13

Message:
Logged In: YES 
user_id=97460

Sorry, I see your point NOW :-)

You say that since "import sys" defines a new local
variable, all "sys" variable usages in that function will be
local. So "retroactively", the first "print sys" fails since
the variable is known as local, and "sys" doesn't still
exist locally at that point.

Now I understand... Thanks. You are right :)

----------------------------------------------------------------------

Comment By: Jesús Cea Avión (jcea)
Date: 2002-09-26 22:02

Message:
Logged In: YES 
user_id=97460

Sorry about the assignament. I apologize.

I don't undestand your comment. Inside the function, first
line, "sys" is used and discovered as "global": "print sys.path"

The second line, the "import"...  I think "import sys"
should inject *a* *new* symbol, "sys", locally. Think about
this, for example:

>>> import sys
>>> def a() :
...   print sys 
...   import email as sys
...   print sys
... 
>>> a()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in a
UnboundLocalError: local variable 'sys' referenced before
assignment

I am not referencing "sys" before use, anyway :-)

----------------------------------------------------------------------

Comment By: Guido van Rossum (gvanrossum)
Date: 2002-09-26 21:20

Message:
Logged In: YES 
user_id=6380

That's a language feature, not a bug. When a variable is
assigned to anywhere in a function body, it's a local
variable everywhere in that function body, and if it's not
defined, you get an UnboundLocalError exception, even if
there's a global variable with the same name.

Please don't assign bugs or set their priority -- that's up
to the triage committee.

----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=615123&group_id=5470