473,809 Members | 2,575 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Don't understand global variables between modules

Hi all

I don't understand globals between multiple modules in a python program. I
really don't. I've narrowed it down to the following two very simple
programs a.py and b.py. When I run a.py I get the following output:

inc: 2
A: 2
inc: 3
B: 3
C: 1
I don't understand the last line at all. Why is my x variable 1 after having
been incremented twice? Is there more than one global space? Is this
backreference to the original a.py not allowed?

I could use some help.

Thanks

Bart van Deenen

a.py:
---------------------------------
import b
x=1

def inc():
global x
x+=1
print "inc: ",x

if __name__=="__ma in__":
b.test()
print "C: ",x

b.py:
---------------------------------
def test():
import a
a.inc()
print "A: ",a.x
a.inc()
print "B: ",a.x

Jul 18 '05 #1
4 1996
Bart wrote:
I don't understand globals between multiple modules in a python program. I
really don't. I've narrowed it down to the following two very simple
programs a.py and b.py. When I run a.py I get the following output:

inc: 2
A: 2
inc: 3
B: 3
C: 1

I don't understand the last line at all. Why is my x variable 1 after having
been incremented twice?
because running a script isn't the same thing as importing it. try adding
"print __name__" lines before your other print statements so you can see
who's printing what.
Is there more than one global space?


in this case, there are more module namespaces than you think.

this page might help (especially the "Using Modules as Scripts" section):

http://effbot.org/zone/import-confusion.htm

</F>

Jul 18 '05 #2

"Bart" <bv******@acces s-four-all.nl.invalid> wrote in message
news:42******** *************@d reader14.news.x s4all.nl...
I don't understand globals between multiple modules in a python program.
Because there are not any. All names are bound to objects in a module
global namespace, a function local namespace, or an object attribute
namespace.

The builtins seem like and act like intermodule 'globals', but their names
are bound in a hidden module which is imported to all other modules and
treated like an extension of each module's namespace. Users can do
something similar by defining a 'myglobals' module and importing it
everywhere.
I've narrowed it down to the following two very simple
programs a.py and b.py. When I run a.py I get the following output:

inc: 2
A: 2
inc: 3
B: 3
C: 1
I don't understand the last line at all.


Don't feel too bad. While I 'know' the answer -- running anyfile.py
creates a module named '__main__' while importing it (in another module)
creates a separate module named 'anyfile' -- it did not 'click' until
reading Fredrik's hint. You created a nice, memorable example that shows
that __main__ is not anotherfile.any file (in this case, not b.a)!

Terry J. Reedy

Jul 18 '05 #3
Fredrik Lundh <fr*****@python ware.com> wrote:
because running a script isn't the same thing as importing it. try adding
"print __name__" lines before your other print statements so you can see
who's printing what.
Is there more than one global space?


in this case, there are more module namespaces than you think.
this page might help (especially the "Using Modules as Scripts" section):
http://effbot.org/zone/import-confusion.htm


Thanks for your answer, and also thanks for effbot. Lots of good tips.

Bart
Jul 18 '05 #4
Hi

thanks for the answer. Coming from C and C++ this behaviour wasn't
really obvious to me. I still love Python though :-) Most elegant
language I've ever seen.

Bart
Jul 18 '05 #5

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

Similar topics

7
4316
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
6
1592
by: dkeeney | last post by:
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 ------------------------------------
10
6725
by: Andy Fish | last post by:
Hi, can anybody put forward a sensible argument javascript's behaviour of creating a new global variable whenever I assign to a previously undeclared variable. I can't beleive this is just for the sake of convenience (surely we learned this much from basic). here's my proposal: all "global" (document scope) variables must be declared by 'var' outside a function block.
9
2383
by: Tony Johansson | last post by:
Hello! I know it's bad design to use global variables. I just want to ask a question about them. Is global variables and global static variables the same. These are define outside any function at the top of the a file where you have them. //Tony
7
3148
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 */
4
7239
by: gamja | last post by:
Hi all. I know that some padding bits are inserted between data members of a structure. Is this rule also applied for the variables on local stack or global??? For example, in following code dumps... ------------ struct foo foo1; .... struct bar bar1;
8
2709
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
2951
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...
8
3826
by: rottmanj | last post by:
. In order to teach my self more. I have started to convert some of my cf scheduled tasks to perl applications. One area where things are kind of fuzzy is setting up global variables that can be called from any module with in an application. So far I have created a farily standard module that will act as my global config. This module will store variables that are populated from the database. So that I will not be forced to re-create/query...
0
9603
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,...
1
10387
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
10120
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
9200
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
7662
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
5550
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...
1
4332
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
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
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.