import and global trouble

D

dag4004

Hello,
I have a strange behavior with global and module.

Here is the module named: foo.py



bar = "egg"



def f1():

global bar

print bar

bar = "bob"

print bar



When i use it :



'egg'

'bob' # It seems to work

'egg' # Damned ! The value is not changing

'bob' # All seems good, grrr !

'bob'



I do not understand.

Is bar a global name?

With which dico do i work?

Is there some thing special to know when we use from --- import *



Is there some one an explanation?



Thanks.

Good hack.



Damien GERANTON
 
A

Alex Martelli

dag4004 wrote:
...
Is there some thing special to know when we use from --- import *

Yes: the short form is "don't".

Always use 'import' (often 'import somelongname as short') and
live happily ever after.

The long form is: "from X import *" assigns a bunch of names
from X (all listed in __all__, or if that's missing all that
don't start with '_') in the current module. Just like assignment,
when you do:

bar1 = 'egg'
bar2 = bar1
bar1 = 'bob'

bar2 is still 'egg', NOT 'bob'. There is no connection between
bar1 and bar2 except that historically at some point they just
happened to reference the same object (due to "bar2 = bar1").

Just the same applies to "from X import *" -- there is no
connection between the names you're assigning in the local
module and those in X, except that at this very moment each
pair happens to reference the same object, just as if you
had assigned them one by one (except that you have no control
on the process, so it's quite accident-prone).


Alex
 
D

Dennis Lee Bieber

dag4004 fed this fish to the penguins on Friday 10 October 2003 03:19
am:
Is bar a global name?
Global essentially means "module level name accessed inside function".
With which dico do i work?

Is there some thing special to know when we use from --- import *
Well... common recommendation is... DON'T use import *

import * makes /copies/ of the names in the importing module. The
global statement is still referencing the name inside the module.

In effect, import * created

__main__.bar
__main__.f1()

but __main__.f1() has a global statement that is referring to foo.bar,
hence you do not see changes in __main__.bar (the bar in __main__ is
still associated with the original value, but the bar in foo has been
changed to the new value).


bar = "egg"

def f1():
global bar
p1()
bar = "bob"
p1()

def p1():
print bar
bob




--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,166
Messages
2,570,907
Members
47,448
Latest member
DeanaQ4445

Latest Threads

Top