473,405 Members | 2,444 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Make variable global

I have a file, "a.py"

blah = None
def go():
global blah
blah = 5
>From the python interpreter I try....
>>from a import *
blah
go()
blah
....i was hoping to see "5" get printed out the second time I displayed
blah, but it doesn't. Now, if I type this same code directly into the
python interpreter it works as i was hoping. what i am missing?

thanks

Mar 21 '07 #1
5 2392
abcd a écrit :
I have a file, "a.py"

blah = None
def go():
global blah
blah = 5
>>From the python interpreter I try....

>>>>from a import *
blah
go()
blah


...i was hoping to see "5" get printed out the second time I displayed
blah, but it doesn't. Now, if I type this same code directly into the
python interpreter it works as i was hoping. what i am missing?
In Python, 'global' means 'module level'. And 'variables' are
name:object bindings in a namespace (mostly function, class or module).
The way you import blah and go from module a creates two names (blah and
go) in the current namespace, and bind these names to resp. a.blah and
a.go. The fact that go rebinds a.blah doesn't impact current namespace's
blah.

The following session may help you understanding what happens:
>>from a import *
dir()
['__builtins__', '__doc__', '__name__', 'blah', 'go']
>>import a
dir()
['__builtins__', '__doc__', '__name__', 'a', 'blah', 'go']
>>dir(a)
['__builtins__', '__doc__', '__file__', '__name__', 'blah', 'go']
>>go is a.go
True
>>go()
blah
a.blah
5
>>>
Note that rebinding a name and mutating a (mutable) object are two
distinct operations:

# b.py
blah = ['42']
def go():
blah[0] = "yo"

def gotcha():
global blah
blah = ['gotcha']
>>from b import *
import b
blah
['42']
>>blah is b.blah
True
>>go()
blah
['yo']
>>b.blah
['yo']
>>blah is b.blah
True
>>gotcha()
blah
['yo']
>>b.blah
['gotcha']
>>>
To make a long story short:
1/ avoid globals whenever possible
2/ when using (module) globals, either use them as pseudoconstants or as
module's 'private' variables (IOW : only functions from the same module
can modify/rebind them).

HTH
Mar 21 '07 #2
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

abcd wrote:
I have a file, "a.py"

blah = None def go(): global blah blah = 5
>From the python interpreter I try....
>>>from a import * blah go() blah

...i was hoping to see "5" get printed out the second time I
displayed blah, but it doesn't. Now, if I type this same code
directly into the python interpreter it works as i was hoping.
what i am missing?

thanks
"import" imports bindings between symbols and objects into
the module from another one. When you call a function in another
module, it changes global space of module where it is defined.
The global space of the module, where caller is in, is kept from touched
except accessing through module names.

- --
Thinker Li - th*****@branda.to th********@gmail.com
http://heaven.branda.to/~thinker/GinGin_CGI.py
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (FreeBSD)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGAZYd1LDUVnWfY8gRAsdNAJ9niVqdGz1aG0NUzN+Ggm k+vnqZSgCfQB9s
SBuV/fWo8lqAytQP/QXQPXE=
=1BiL
-----END PGP SIGNATURE-----

Mar 21 '07 #3
abcd wrote:
I have a file, "a.py"

blah = None
def go():
global blah
blah = 5
From the python interpreter I try....

>>>from a import *
blah
go()
blah


...i was hoping to see "5" get printed out the second time I displayed
blah, but it doesn't. Now, if I type this same code directly into the
python interpreter it works as i was hoping. what i am missing?
Since procedure go is defined in a.py, the global blah it refers to
is global to that module.

So import a (instead of importing * from a) and try this:
>>import a
a.blah
a.go()
a.blah
5
>>>

Gary Herron

Mar 21 '07 #4
try
>>import a
a.blah
a.go()
a.blah
or

rewrite a.py like this

blah = [ None ]
def go():
global blah
blah[0] = 5 # and not blah=[5]

then
>>from a import *
blah
go()
blah
will work as expected

in case 1 ( import a )

blah in a.py and a.blah in python interpreter are the same
_REFERENCE_, they are the same

in case 2 (blah[0]=5)

blah in a.py and a.blah in python interpreter are just 2 differents
variables
that reference the _SAME_ object, but here (the difference with your
original case)
the object ( a list ) is a mutable object (you can change its value
without changing
the object. Here blah=[5] should simply make blah reference a new
object, but will
let the old one, [None] untouched, but unreachable (no more reference
to it)

BR

On 21 mar, 20:55, "abcd" <codecr...@gmail.comwrote:
I have a file, "a.py"

blah = None
def go():
global blah
blah = 5
From the python interpreter I try....
>from a import *
blah
go()
blah

...i was hoping to see "5" get printed out the second time I displayed
blah, but it doesn't. Now, if I type this same code directly into the
python interpreter it works as i was hoping. what i am missing?

thanks

Mar 21 '07 #5
abcd wrote:
I have a file, "a.py"

blah = None
def go():
global blah
blah = 5
>>From the python interpreter I try....
>>>from a import *
blah
go()
blah

...i was hoping to see "5" get printed out the second time I displayed
blah, but it doesn't. Now, if I type this same code directly into the
python interpreter it works as i was hoping. what i am missing?

thanks
That "blah" is global to module a, not to the whole program. You import
all names from a, which creates a blah and a go in your local namespace,
bound to the sames values those names have in module a.

When you call go() this sets a.blah to 5, but __main__.blah is still None.

It's those dratted namespaces again!

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings http://holdenweb.blogspot.com

Mar 21 '07 #6

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

Similar topics

7
by: djc | last post by:
I have several subroutines (all inline code) that wind up using the same database connection object variable. I have been declaring a new variable in every sub. I just now came to a point where I...
6
by: Water Cooler v2 | last post by:
I want to take a global variable in my ASP.NET application. How do I make it global so that it is accessible to all the pages in my application? Do I put it in the Global.asax file? If so,...
4
by: David Wheeler | last post by:
4.8-STABLE FreeBSD 4.8-STABLE i386 sahlins# cd postgresql-7.4.2/contrib/pg_autovacuum sahlins# make "../../src/Makefile.global", line 38: Missing dependency operator...
12
by: a | last post by:
def fn(): for i in range(l) global count count= .... how do i declare count to be global if it is an array subsequently i should access or define count as an array error:
2
by: sairam | last post by:
I have some local variables defined in one method and Can I make those variables as global variables? If so , can any one explain me how can I do that Thanks, Sairam
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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,...
0
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...

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.