473,903 Members | 3,373 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 3129
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
4496
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
3120
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
2605
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
19071
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
2150
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
8105
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
2553
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
2166
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
2992
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
11291
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...
0
10882
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
10988
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
9692
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...
0
5897
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
6099
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4732
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
4312
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3327
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.