473,626 Members | 3,221 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why I need to declare import as global in function

I have a stange side effect in my project :

in my project I need to write "gobal" to use global symbol :

....
import math
....
def f() :
global math # necessary ?????? else next line generate an error
message ?????
print math.pi

(the problem is for all global module symbol)

I have certainly change somthing in my project, but I can't find what ?

(just a small program wort fine without this global of course)

Can anybody help me : where can I search the mistake in my project ?

Nov 28 '05 #1
16 3099
Sounds like something, either in your program, in another lib you
imported, or perhaps some extension you recently installed (and which
automatically starts), overrides 'import' (replaces it with it's own
version) -- and forgets to add the imported modules properly to the
globlals?
Or something, some option, that perhaps changes the way that Python
recognizes globals?

If you declare another global variable, then try to use it in your
function, then what's the result?

What Python version do you use?

cheers,

--Tim

Nov 28 '05 #2
di************* @gmail.com wrote:
I have a stange side effect in my project :

in my project I need to write "gobal" to use global symbol :

...
import math
...
def f() :
global math # necessary ?????? else next line generate an error
message ?????
what error message?
print math.pi


you only need global in this case if you assign to the name somewhere
later in the function (e.g. "math = ..." or "import math" or some other
assignment)

please post the error message (the entire traceback).

</F>

Nov 28 '05 #3
the error message :

EXCEPTION RAISED::

Traceback (most recent call last):
File "../tu.py", line 21, in run_tu
execfile( filename )
File "TU_05_010. py", line 8, in ?
import TU_05_tools
File "./TU_05_tools.py" , line 4, in ?
f()
File "./TU_05_tools.py" , line 2, in f
print math.pi
NameError: global name 'math' is not defined

I have remarq that this problem is raised when I execute code in an
imported module (during importation)

I think I will be able to isolate it and have a simple sample soon ....

Nov 29 '05 #4
wrote:
I have remarq that this problem is raised when I execute code in an
imported module (during importation)

I think I will be able to isolate it and have a simple sample soon ....

Meanwhile, try adding:

import math

to the top of TU_05_tools.py.
Nov 29 '05 #5
di************* @gmail.com wrote:
the error message :

EXCEPTION RAISED::

Traceback (most recent call last):
File "../tu.py", line 21, in run_tu
execfile( filename )
File "TU_05_010. py", line 8, in ?
import TU_05_tools
File "./TU_05_tools.py" , line 4, in ?
f()
File "./TU_05_tools.py" , line 2, in f
print math.pi
NameError: global name 'math' is not defined

I have remarq that this problem is raised when I execute code in an
imported module (during importation)

I think I will be able to isolate it and have a simple sample soon ....


Random guess: change the execfile() call to

execfile(filena me, globals())

or

exec file(filename). read()

If one of the above works, a minimal example of what happens could be

file("tmp.py", "w").write( """
import math
""")

def f():
execfile("tmp.p y")
print locals()["math"].pi # 3.14159265359
print math.pi # Error, math looked up in the global
namespace

f()

execfile() puts symbols into the local namespace but keeps the compiler
clueless because it's just an ordinary function, whereas exec triggers the
generation of slightly different bytecode for the enclosing function.

Peter

Nov 29 '05 #6
Peter Otten wrote:
Traceback (most recent call last):
File "../tu.py", line 21, in run_tu
execfile( filename )
File "TU_05_010. py", line 8, in ?
import TU_05_tools
File "./TU_05_tools.py" , line 4, in ?
f()
File "./TU_05_tools.py" , line 2, in f
print math.pi
NameError: global name 'math' is not defined

I have remarq that this problem is raised when I execute code in an
imported module (during importation)

I think I will be able to isolate it and have a simple sample soon ....


Random guess: change the execfile() call to

execfile(filena me, globals())

or

exec file(filename). read()


That is unlikely to help. The execfile target seems to have been
TU_05_010.py, but the file which cannot access math is TU_05_tools.py
accessed by a normal import, so adding some globals to the execfile call
won't really do anything useful.

Isn't it fun trying to guess the problem in the absence of the code?
Nov 29 '05 #7
Duncan Booth wrote:
Isn't it fun trying to guess the problem in the absence of the code?


What other reason could there be to forego the sane approach -- stick
'import math' everywhere it might belong?
Those exec/execfile() peculiarities are so much more interesting ;-)

Peter

Nov 29 '05 #8
Duncan Booth wrote:
That is unlikely to help. The execfile target seems to have been
TU_05_010.py, but the file which cannot access math is TU_05_tools.py
accessed by a normal import, so adding some globals to the execfile call
won't really do anything useful.

Isn't it fun trying to guess the problem in the absence of the code?


given that the NameError occurs on line 2 of the file, inside a function, this
is probably just a misunderstandin g of how namespaces work in Python...

</F>

Nov 29 '05 #9
You're right, the problem is around the usage of "execfile".

But I have still difficulties to get a simple sample.... and have no
enough time to work on it until end of week.

I will post if I resolve my problem or if I can get a simple sample.

Nov 29 '05 #10

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

Similar topics

2
4488
by: dag4004 | last post by:
Hello, I have a strange behavior with global and module. Here is the module named: foo.py bar = "egg"
10
3090
by: Jeff Wagner | last post by:
I am in the process of learning Python (obsessively so). I've been through a few tutorials and read a Python book that was lent to me. I am now trying to put what I've learned to use by rewriting that Numerology program I wrote years ago in VB. There are times I am totally stuck (for instance, I just had an idea to put the numerical values of the alphabet and months of the year in a dictionary located in a function. Then, I can import the...
3
2591
by: Brad Clements | last post by:
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...
6
19052
by: rick | last post by:
Noob problem. I prefer to keep all my scripts in an external '.js' file. I am currently loading the external '.js' file from the header. Problem is I would like to declare a global variable in the external file, but I keep getting an error about the object does not exist. Can someone tell me where or how to declare a global variable in an external file that is available after the page is loaded.
1
2137
by: RJ Web | last post by:
I have a DOS program that needs to run in a Full Screen DOS window when running on WIN2000. I have not discoverd how to set up the call such that WIN2000 switches to full screen mode, as if I pressed ALT+Enter. The program I'm trying to run will not execute properly unless I switch to full screen.
8
8082
by: yinglcs | last post by:
Hi, I have the following code: colorIndex = 0; def test(): print colorIndex; This won't work. But it works if i do this:
4
2538
by: =?Utf-8?B?UHVjY2E=?= | last post by:
The function that I'm trying to call through DLLImport has a parameter that has a C code's vector's Itrator to a structure. I Have marshalled the structure in C# but how do I do the C type vector's Iterator in C#? The problem is in the next line and the rest of the code is just additional information on what I'm doing. Thanks. CUnityDS.DE_ERRORS errcode = CUnityDS.LibWrap.EncodeAsnUser(ref blob, userContextData); //In & out...
7
2147
by: bambam | last post by:
import works in the main section of the module, but does not work as I hoped when run inside a function. That is, the modules import correctly, but are not visible to the enclosing (global) scope. Questions: (1) Where can I read an explanation of this? (2) Is there a work around?
6
2977
by: zaina | last post by:
hi everybody i am nwebie in this forum but i think it is useful for me and the member are helpful my project is about connecting client with the server to start exchanging messages between them. to be more clear we process this purpose we serve this to the student in the university. how?? student will send a message that contains his name,id and request by format the server want such as zaina-20024008-grade. the grade is the request...
0
8637
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8364
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
8504
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
7193
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6125
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5574
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
4197
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2625
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
2
1511
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.