473,770 Members | 4,419 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Global variables and modules


I have a newby type question on how global variables work between
modules.

I have a module test2.py that defines a global variable as well as two
functions to operate on that variable. A script test1.py imports the
three names and prints out values of the global between operations, and
the results aren't what I expected.

Here is the module, test2.py
------------------------------------
glbl = 25

def inc_glbl():
global glbl
glbl += 1

def get_glbl():
global glbl
return glbl
------------------------------------

and here is the test script, test1.py
-------------------------------------

from test2 import glbl, inc_glbl, get_glbl

print 'glbl orig ', glbl

inc_glbl()
print 'glbl postinc ', glbl

new = get_glbl()
print 'glbl from func ', new
--------------------------------------
I would expect the three values to be ( 25, 26, 26 ), but what I get is
c:\projects\pit cher_model>test 1.py
glbl orig 25
glbl postinc 25
glbl from func 26

---------
It seems that the references to 'glbl' are seeing a local copy, rather
than the original. This is not what the literature says should be
happening. I am looking for a way to share data between modules. Can
you advise me on my error? I am using Python 2.3.2 from ActiveState,
on Windows XP Pro.

Thank you
David

Jul 18 '05 #1
6 1590
<dk*****@travel byroad.net> wrote:
...
and here is the test script, test1.py
-------------------------------------

from test2 import glbl, inc_glbl, get_glbl
Think of this as roughly equivalent to:

import locl
glbl = test2.glbl

and so on. That is, after the 'from test2 import', the two names
test1.glbl and test2.glbl refer to the same object. But if you now
rebind name test2.glbl to refer to a distinct object, that of course has
no effect on name test1.glbl.
I would expect the three values to be ( 25, 26, 26 ), but what I get is
Why? Take an equivalent:

a = 25
b = a
a = 26

would you now expect name b to be magically rebound to 26? If so, then
you have a very peculiar mental model for name/value correspondences ,
one that doesn't happen to hold in any language I know, surely not in
Python. To repeat a commonly used metaphor: think of names as post-it
notes that may be attached to some piece of furniture, and moved from
one to another. The notes are NOT attached to each other, but rather to
the objects: moving one post-it does not affect other post-its.
It seems that the references to 'glbl' are seeing a local copy, rather
No copy whatsoever is involved. After the assignment (binding) you do
with 'from test2 import', names test1.glbl and test2.glbl refer to the
same object (value). If you now rebind either name, the other is
unaffected.
than the original. This is not what the literature says should be
happening.
If you can point to sentences in "the literature" which have misled you
into believing a different behavior would be expected, I'll do my best
to fix those sentences (as a book and article author, editor, reviewer,
and Python contributor). While the Python docs, including books &c, are
far from perfect, I doubt there is any such blooper left in them.
I am looking for a way to share data between modules. Can


If you really must, consider using a container object. The most
suitable container object for these tasks is often a module. I.e.,
code, in test1:

import test2

and then refer to test2.glbl throughout. I.e., forget 'from', use
'import'.

As I wrote in Python in a Nutshell, p. 120, last paragraph before
"Module Loading":
"""
In general, the import statement is a better choice than the from
statement. I suggest you think of the from statement [...] as [a]
convenience meant only for occasional use in interactive Python
sessions. If you always access module M with the statement import M,
and always access M's attributes with explicit syntax M.A, your code
will be slightly less concise, but far clearer and more readable.
"""

I don't know how I could have put this advice more strongly or more
directly (I continue with explanations about the cases in which 'from'
is instead appropriate, chiefly getting single modules from packages).

Giving strong direct advice, rather than just reference info, in a book
of the "in a Nutshell" series, is not common, but I do it quite a bit;
after all, "how does Python work exactly", e.g. the fact that 'from X
import Y' is almost the same as 'Y = X.Y', is pretty simple to explain,
and so takes up little space -- OTOH, the consequences of this, such as
"thus, generally, don't use 'from', use 'import'" may not be obvious to
readers, so I point them out directly.

Of course, that doesn't help much if people don't _read_ it;-).
Alex
Jul 18 '05 #2
Add these lines to test1.py and see what you get:
import test2
print 'test2.glbl postinc ', test2.glbl

This will work as you expect.

Next try chaning glbl in test2 to a list (a mutable type).

test2.py:
glbl = [25]

def inc_glbl():
global glbl
glbl[0] = glbl[0] + 1

def get_glbl():
global glbl
return glbl[0]

test1.py:
from test2 import glbl, inc_glbl, get_glbl

print 'glbl orig ', glbl[0]

inc_glbl()
print 'glbl postinc ', glbl[0]

new = get_glbl()
print 'glbl from func ', new

import test2
print 'test2.glbl postinc ', test2.glbl

[kbinu@localhost kbinu]$ python2.2 test.py
glbl orig 25
glbl postinc 26
glbl from func 26
test2.glbl postinc [26]
On 23 Dec 2004 21:43:40 -0800, dk*****@travelb yroad.net
<dk*****@travel byroad.net> wrote:

I have a newby type question on how global variables work between
modules.

I have a module test2.py that defines a global variable as well as two
functions to operate on that variable. A script test1.py imports the
three names and prints out values of the global between operations, and
the results aren't what I expected.

Here is the module, test2.py
------------------------------------
glbl = 25

def inc_glbl():
global glbl
glbl += 1

def get_glbl():
global glbl
return glbl
------------------------------------

and here is the test script, test1.py
-------------------------------------

from test2 import glbl, inc_glbl, get_glbl

print 'glbl orig ', glbl

inc_glbl()
print 'glbl postinc ', glbl

new = get_glbl()
print 'glbl from func ', new
--------------------------------------
I would expect the three values to be ( 25, 26, 26 ), but what I get is
c:\projects\pit cher_model>test 1.py
glbl orig 25
glbl postinc 25
glbl from func 26

---------
It seems that the references to 'glbl' are seeing a local copy, rather
than the original. This is not what the literature says should be
happening. I am looking for a way to share data between modules. Can
you advise me on my error? I am using Python 2.3.2 from ActiveState,
on Windows XP Pro.

Thank you
David

--
http://mail.python.org/mailman/listinfo/python-list

Jul 18 '05 #3

Thank you to both of you for your assistance.

Using the qualified 'test2.glbl' form of the variable name gives the
result I need. The concepts of binding and rebinding, as programming
concerns, are new to me; I will have to study that further.
Thank you again, and Merry Christmas.

David

Jul 18 '05 #4
Alex Martelli said unto the world upon 2004-12-24 03:23:
<dk*****@travel byroad.net> wrote:
<SNIP>
If you really must, consider using a container object. The most
suitable container object for these tasks is often a module. I.e.,
code, in test1:

import test2

and then refer to test2.glbl throughout. I.e., forget 'from', use
'import'.

As I wrote in Python in a Nutshell, p. 120, last paragraph before
"Module Loading":
"""
In general, the import statement is a better choice than the from
statement. I suggest you think of the from statement [...] as [a]
convenience meant only for occasional use in interactive Python
sessions. If you always access module M with the statement import M,
and always access M's attributes with explicit syntax M.A, your code
will be slightly less concise, but far clearer and more readable.
"""

I don't know how I could have put this advice more strongly or more
directly (I continue with explanations about the cases in which 'from'
is instead appropriate, chiefly getting single modules from packages).

Giving strong direct advice, rather than just reference info, in a book
of the "in a Nutshell" series, is not common, but I do it quite a bit;
after all, "how does Python work exactly", e.g. the fact that 'from X
import Y' is almost the same as 'Y = X.Y', is pretty simple to explain,
and so takes up little space -- OTOH, the consequences of this, such as
"thus, generally, don't use 'from', use 'import'" may not be obvious to
readers, so I point them out directly.

Of course, that doesn't help much if people don't _read_ it;-).
Alex


Hi all,

I'm quite fond of the

import really_long_mod ule_name as rlmn

idiom. I use it all the time for some utility modules that I have
developed, where I like the module to have a descriptive name, but I
don't feel like burning line-length on retyping it all the time. If you
adopt a standard set of abbreviations ('fu' for 'fileutils', etc.) you
get less typing while preserving the advantages of clarity and
readability that the unmodified import provides. (And, of course, both
protect your namespace from the clobbering that will eventually arise
with use of from.)

I don't think the relevant section of Nutshell mentions this idiom.
However, I don't have my copy with me (seasonal travel, and all), so
apologies if my memory leads me astray.

For what its worth, I'm glad for the advice in Nutshell. It transforms
the book from a useful thing for those who like dead-tree references
into a text one can actually read (as opposed to merely consult quickly).

Best to all,

Brian vdB

Jul 18 '05 #5
Brian van den Broek <bv****@po-box.mcgill.ca> wrote:
I'm quite fond of the

import really_long_mod ule_name as rlmn ... I don't think the relevant section of Nutshell mentions this idiom.
However, I don't have my copy with me (seasonal travel, and all), so
apologies if my memory leads me astray.


Apologies accepted -- it's right on p. 117, at the first mention of the
import statement. Maybe I'm not giving it enough prominence, though,
nor advice about how to use it...
Alex
Jul 18 '05 #6

dk*****@travelb yroad.net wrote:
I have a newby type question on how global variables work between
modules.

I have a module test2.py that defines a global variable as well as two functions to operate on that variable. A script test1.py imports the
three names and prints out values of the global between operations, and the results aren't what I expected. [snip] I am looking for a way to share data between modules. Can
you advise me on my error?


Yes. Your error is that you are looking at global variables as "a way
to share data between modules". The advice is "Don't do that". Limited
use of global variables whose values are updated is barely tolerable
within a single module that will be executed by a single thread of a
single process. Otherwise you can end up with monstrosities like
database "forms" applications with hundreds of globals. Google for
concepts like "modularity " and "informatio n hiding". Then read about
OOP.

Jul 18 '05 #7

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

Similar topics

7
16749
by: Fuming Wang | last post by:
Hi, I have several modules that need to access global variables among them. I can do that by import modules: module A: gA = 'old' module B: import A
7
4315
by: Aaron Deskins | last post by:
I'm trying to write program with a main.py and several functions distributed in auxiliary *.py files. I've looked through the archives on the 'global' keyword, but I'm still not sure how to get this right. I want to be able to have some variables that can be accessed/changed by many modules/functions. Here's an example. ____________ main.py
17
5630
by: MLH | last post by:
A97 Topic: If there is a way to preserve the values assigned to global variables when an untrapped runtime error occurs? I don't think there is, but I thought I'd ask. During development, I'm constantly running tests on imperfect code. On of the cumbersome jobs encountered is reassigning global vars their values after a close encounter with an untrapped runtime error. Rather than writing a procedure to simply reassign them all with a...
33
3050
by: MLH | last post by:
I've read some posts indicating that having tons of GV's in an Access app is a bad idea. Personally, I love GVs and I use them (possibly abuse them) all the time for everything imaginable - have been for years. If the machine has memory to spare and windows can use it - I'm thinking "Why not?" I was wondering what some of you have to say about that, particularly any severe "gotchas" you've had the unfortunate experience to contend with.
11
2566
by: Capstar | last post by:
Hi, I am working on an application, which will run embedded without an OS. The app is build up out of a couple of well defined parts. At first I wanted to keep those parts seperated and use opaque data types to transfer information in between them. At some stage I was stuck and needed to make a variable global, and I also needed to make the struct declaration public to some other parts. Looking through the code I found out that lots...
7
3145
by: Michael | last post by:
Hi newsgroup, as the subject indicates I am looking for an advice using global variables. I am not if this problem is more about style then C. If its wrong in thi group, sorry. So I have a couple of function that all need the same information (all located in the same file). By now it looks like /* file beginns */
25
66084
by: Daniel Bass | last post by:
how do i declare a global variable in c#.net? it's like it want's everything in classes... there are times when globals are good, like having constants in a program which apply to several layers/objects/etc... or does it expect me to create a singleton global class structure? surely it's not that terrible.
8
2704
by: newbie | last post by:
Hello, I have questions about global variables in OOP (in general) and Python (in specific). I understand (I think) that global variables are generally not a good idea. However, if there are variables that need to be accessed by a number of classes that exists in separate namespaces (files), what would be the best way to do this? So far, I have approached the problem by making the variables attributes of one class and passing...
18
2947
by: robert | last post by:
Using global variables in Python often raises chaos. Other languages use a clear prefix for globals. * you forget to declare a global * or you declare a global too much or in conflict * you have a local identical variable name and want to save/load it to/from the global with same name * while you add code, the definition of globals moves more and more apart from their use cases -> weirdness; programmers thinking is fragmented * using...
0
9602
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9439
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
10237
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
9882
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...
1
7431
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
6690
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
5326
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...
2
3589
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2832
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.