473,732 Members | 1,921 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Weird import behavior

Hi,

I have been using Python for a while but today I came across a really
strange behavior:

While poking around in Queue.py due to problems with importing this
module from a thread I got an error that a module that I imported on
top of the file could not be accessed. I reduced the problem to this
small script:

import string
import os

class T:
def __init__(self):
try:
print 'xxx nothing to do'
except ImportError:
print 'got an import error'
import os as string

print 'xxxx string module', string

t=T()
The import clause in the except statement (although never executed)
removes the reference to the string module imported at the beginning of
the script. Any idea why this is the case?

Thanks,
Tommy

Oct 25 '05 #1
5 1669
Tommytrojan wrote:
import string
import os

class T:
def __init__(self):
try:
print 'xxx nothing to do'
except ImportError:
print 'got an import error'
import os as string

print 'xxxx string module', string

t=T()
The import clause in the except statement (although never executed)
removes the reference to the string module imported at the beginning of
the script. Any idea why this is the case?


Quoting the error message would have made the answer instantly clear to
everyone, including probably yourself:

UnboundLocalErr or: local variable 'string' referenced before assignment

Assigning to the variable 'string' anywhere in the function makes it a
local variable throughout the function. Use 'global string' if you want the
import to affect the global variable.
Oct 25 '05 #2
Duncan,

thanks for your quick reply. I guess I should have included the output.
I thought I was clear in the error description.
The problem is that I never assign to 'string'. I only reference it (as
the error message correctly states). If you comment out the import
statement in the except clause the program runs fine. Now notice that
the exception hander never gets executed! Any explanation?

Oct 25 '05 #3
Tommytrojan wrote:
Duncan,

thanks for your quick reply. I guess I should have included the output.
I thought I was clear in the error description.
The problem is that I never assign to 'string'. I only reference it (as
the error message correctly states). If you comment out the import
statement in the except clause the program runs fine. Now notice that
the exception hander never gets executed! Any explanation?

You have an assignment to 'string' in the function (import, class and def
statements are all equivalent to assignment statements so far as scoping
is concerned). It doesn't matter whether or not the assignment gets
executed: the compiler flags the variable as a local variable.

See the Python FAQ, 1.2.2:

1.2.2 What are the rules for local and global variables in Python?

In Python, variables that are only referenced inside a function are
implicitly global. If a variable is assigned a new value anywhere within
the function's body, it's assumed to be a local. If a variable is ever
assigned a new value inside the function, the variable is implicitly local,
and you need to explicitly declare it as 'global'.
Oct 25 '05 #4
"Tommytroja n" wrote:
thanks for your quick reply. I guess I should have included the output.
I thought I was clear in the error description.
The problem is that I never assign to 'string'. I only reference it (as
the error message correctly states). If you comment out the import
statement in the except clause the program runs fine. Now notice that
the exception hander never gets executed! Any explanation?


the language reference has the full story:

http://docs.python.org/ref/naming.html

"If a name is bound in a block, it is a local variable of that
block." /.../

"The following constructs bind names: formal parameters
to functions, import statements, class and function definitions
(these bind the class or function name in the defining block),
and targets that are identifiers if occurring in an assignment,
for loop header, or in the second position of an except
clause header. The import statement of the form "from ...
import *" binds all names defined in the imported module,
except those beginning with an underscore. /.../

A target occurring in a del statement is also considered bound
for this purpose (though the actual semantics are to unbind
the name). /.../

If a name binding operation occurs anywhere within a code block,
all uses of the name within the block are treated as references to
the current block."

</F>

Oct 26 '05 #5
Thanks for the clarification. I never ran into this before although I
have been working with Python for over 8 years. Good to learn something
new.

Cheers,
Thomas

Oct 26 '05 #6

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

Similar topics

0
1427
by: newgene | last post by:
Hi, group, A weird clipboard behavior for your help: ==============Code============== from Tkinter import * import tkMessageBox root=Tk() root.withdraw() root.clipboard_clear()
0
1210
by: Ted Gill | last post by:
Platform: Windows ME Python version: 2.3.2-1 Problem: Running GUI apps in Idle does not work. When executing GUI (tkinter/pmw) apps from the edit windows or doing an "import <file>" in the shell window GUI apps freeze and do not respond to internal widgets or window decoration. They also do not repaint. Only way to bail out is to restart the interpreter. Same apps work fine from DOS window or double-clicked in file manager. These...
11
13721
by: Les Paul | last post by:
I'm trying to design an HTML page that can edit itself. In essence, it's just like a Wiki page, but my own very simple version. It's a page full of plain old HTML content, and then at the bottom, there's an "Edit" link. So the page itself looks something like this: <HTML><HEAD><TITLE>blah</TITLE></HEAD><BODY> <!-- TEXT STARTS HERE --> <H1>Hello World!</H1> <P>More stuff here...</P>
1
5899
by: Jonathan Yong | last post by:
I observe a very weird behavior when dynamically create web control and bind events to it. Create a C# ASP.NET application, Put a PlaceHolder and Textbox onto the Web form, and try with the 4 code scenerio below. --------------------------------------------------------------------------- Scenerio 1
0
1347
by: spacelabstudio | last post by:
Hi, I'm observing some weird behavior and have written the following test program to demonstrate. This works under cygwin/WinXP but not Gentoo(kernel 2.6): huh.py ------------------------------------------- import pty,os,sys # Fork ( pid, fd ) = pty.fork()
5
1712
by: Pupeno | last post by:
Hello, I am experiencing a weird behavior that is driving me crazy. I have module called Sensors containing, among other things: class Manager: def getStatus(self): print "getStatus(self=%s)" % self return {"a": "b", "c": "d"} and then I have another module called SensorSingleton that emulates the
7
20564
by: Ron Adam | last post by:
from __future__ import absolute_import Is there a way to check if this is working? I get the same results with or without it. Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) on win 32 _Ron
0
1474
by: David | last post by:
On Wed, Apr 30, 2008 at 6:42 PM, Sean Ryan <searyan@gmail.comwrote: If -v makes a difference, it is most likely due to timing. The output to console slows down your app enough so that the ImportError doesn't get raised. Try piping output to a text file. Also experiment with the -u (unbuffered output) option. Another possibility is that the python binary that runs (when you launch with -v) is different to the one that the script...
1
1368
by: jwahlmann | last post by:
I'm experiencing some strange behavior when starting up python on a Debian-based PowerPC platform. Normally, I operate from this platform with a root file system on an IDE flash drive (/dev/hda1). However, I'm trying to get my system to run with root on a mechanical SATA drive (/dev/sda1). Both are installed on a PowerPC board via a PMC daughter board. When running off the flash drive, the Python interpreter loads and runs just fine....
0
8773
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9445
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9234
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9180
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6030
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4548
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4805
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3259
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2177
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.