473,732 Members | 2,205 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

persisting data within a module

I'm having trouble understanding how namespaces work in modules. I want to
execute a module within the interpreter and then have values that are
calculated persist so that other modules that get executed can retrieve them.

For example, consider the two simple modules below. The first method fails
and I'm not sure exactly why. (Note: assume one instance of an interpreter.
In my case a 3rd party software tool that starts an interpreter when it
launches).
Two alternate ways of running it:

1. (FAILS: RESULTS A = 0) Use the module "test" itself as the driver using
the conditional statement if (__name__=="__m ain__"):

test.py
run2.py

or,

2. (SUCCES: RESULTS A = 10) Use "run.py" as the driver.

run.py


_________test.p y______________ ____
import sys,os

A = 0

def getA():
global A
return A

def run():
global A
A = 10

if (__name__=="__m ain__"):
run()
_________run.py _______________ ___

import test

test.run()
print "A = " + str(test.getA() )

_________run2.p y______________ ____

import test

print "A = " + str(test.getA() )

--
Peter Bismuti
Boeing Information Technology
Renton, WA
(425) 234-0873 W
(425) 442-7775 C
Nov 13 '07 #1
4 1657
On Nov 12, 5:30 pm, "Peter J. Bismuti" <peter.j.bism.. .@boeing.com>
wrote:
I'm having trouble understanding how namespaces work in modules. I want to
execute a module within the interpreter and then have values that are
calculated persist so that other modules that get executed can retrieve them.
Modules retain state their state across all imports in the same
interpreter instance. Module state is not shared among different
instances of the interpreter.
For example, consider the two simple modules below. The first method fails
and I'm not sure exactly why. (Note: assume one instance of an interpreter.
In my case a 3rd party software tool that starts an interpreter when it
launches).

Two alternate ways of running it:

1. (FAILS: RESULTS A = 0) Use the module "test" itself as the driver using
the conditional statement if (__name__=="__m ain__"):

test.py
run2.py
Ok, what do you mean by this? Do you mean run test.py and then run
run2.py? In so, then you will have *two* instances -- one for each
file being executed. You can only have one main module per
interpreter instance. I suspect this is the source of your confusion.
or,

2. (SUCCES: RESULTS A = 10) Use "run.py" as the driver.

run.py

_________test.p y______________ ____

import sys,os

A = 0

def getA():
global A
return A

def run():
global A
A = 10

if (__name__=="__m ain__"):
run()
Here, A is only initialized when the module is loaded iff it is the
main module. If it's not the main module, then it will have A set to
0 until some other code calls run().
_________run.py _______________ ___

import test

test.run()
print "A = " + str(test.getA() )
This code calls test.run(), which is necessary for A to be 10.
_________run2.p y______________ ____

import test

print "A = " + str(test.getA() )

--
This code gets the value of test.A without calling test.run(). Since
test.run() was not called, A is the value it was initialized when the
test module was loaded -- namely, 0.

Hope this helps,

--Nathan Davis

Nov 13 '07 #2
I'm not sure how to better state my question than to post my code.

The question boils down to which namespace to variable in the module (in this
case A) end up in depending on whether or not the module is simply imported
by another module which acts as the driver (run.py is __main__), or when the
module drives itself (test.py __main__).

For example: my guess is that in the first case A ends up in the namespace of
test and could be referenced by test.A, in the second case A ends up in the
global namespace (and therefore must be referred to as simply A by other
modules).

Can anyone please shed some light on this for me?

Thanks
I'm having trouble understanding how namespaces work in modules. I want
to execute a module within the interpreter and then have values that are
calculated persist so that other modules that get executed can retrieve
them.

Modules retain state their state across all imports in the same
interpreter instance. Module state is not shared among different
instances of the interpreter.
For example, consider the two simple modules below. The first method
fails and I'm not sure exactly why. (Note: assume one instance of an
interpreter. In my case a 3rd party software tool that starts an
interpreter when it launches).

Two alternate ways of running it:

1. (FAILS: RESULTS A = 0) Use the module "test" itself as the driver
using the conditional statement if (__name__=="__m ain__"):

test.py
run2.py

Ok, what do you mean by this? Do you mean run test.py and then run
run2.py? In so, then you will have *two* instances -- one for each
file being executed. You can only have one main module per
interpreter instance. I suspect this is the source of your confusion.
or,

2. (SUCCES: RESULTS A = 10) Use "run.py" as the driver.

run.py

_________test.p y______________ ____

import sys,os

A = 0

def getA():
global A
return A

def run():
global A
A = 10

if (__name__=="__m ain__"):
run()

Here, A is only initialized when the module is loaded iff it is the
main module. If it's not the main module, then it will have A set to
0 until some other code calls run().
_________run.py _______________ ___

import test

test.run()
print "A = " + str(test.getA() )

This code calls test.run(), which is necessary for A to be 10.
_________run2.p y______________ ____

import test

print "A = " + str(test.getA() )

--

This code gets the value of test.A without calling test.run(). Since
test.run() was not called, A is the value it was initialized when the
test module was loaded -- namely, 0.

Hope this helps,

--Nathan Davis
--
Peter Bismuti
Boeing Information Technology
Renton, WA
(425) 234-0873 W
(425) 442-7775 C
Nov 13 '07 #3
How is that state different depending on whether a module has been simply
imported (#2. some other block of code has __name__ == "__main__") and the
script itself being run (#1. and having __name__=="__ma in__")?

Ultimately, what I want is for a module to remember (persist) the value of A,
regardless of how the module has been loaded into the interpreter.

Thanks
Modules retain state their state across all imports in the same
interpreter instance. Module state is not shared among different
instances of the interpreter.
For example, consider the two simple modules below. The first method
fails and I'm not sure exactly why. (Note: assume one instance of an
interpreter. In my case a 3rd party software tool that starts an
interpreter when it launches).

Two alternate ways of running it:

1. (FAILS: RESULTS A = 0) Use the module "test" itself as the driver
using the conditional statement if (__name__=="__m ain__"):

test.py
run2.py

Ok, what do you mean by this? Do you mean run test.py and then run
run2.py? In so, then you will have *two* instances -- one for each
file being executed. You can only have one main module per
interpreter instance. I suspect this is the source of your confusion.
or,

2. (SUCCES: RESULTS A = 10) Use "run.py" as the driver.

run.py

_________test.p y______________ ____

import sys,os

A = 0

def getA():
global A
return A

def run():
global A
A = 10

if (__name__=="__m ain__"):
run()

Here, A is only initialized when the module is loaded iff it is the
main module. If it's not the main module, then it will have A set to
0 until some other code calls run().
_________run.py _______________ ___

import test

test.run()
print "A = " + str(test.getA() )

This code calls test.run(), which is necessary for A to be 10.
_________run2.p y______________ ____

import test

print "A = " + str(test.getA() )

--

This code gets the value of test.A without calling test.run(). Since
test.run() was not called, A is the value it was initialized when the
test module was loaded -- namely, 0.

Hope this helps,

--Nathan Davis
--
Peter Bismuti
Boeing Information Technology
Renton, WA
(425) 234-0873 W
(425) 442-7775 C
Nov 13 '07 #4
En Tue, 13 Nov 2007 13:09:01 -0300, Peter J. Bismuti
<pe************ *@boeing.comesc ribió:
How is that state different depending on whether a module has been simply
imported (#2. some other block of code has __name__ == "__main__") and
the
script itself being run (#1. and having __name__=="__ma in__")?
It's not different at all, or I don't understand the question.
Ultimately, what I want is for a module to remember (persist) the value
of A,
regardless of how the module has been loaded into the interpreter.
It doesn't care. If you have a variable A in (the global namespace of) a
module, it's there, no matter how the module has been loaded. A namespace
has no concept of "history", it's just a mapping from names to objects.

Unless you're talking about this situation (should be on the FAQ, but I
can't find it):

--- begin one.py ---
A = 1

if __name__=='__ma in__':
print "In one.py, A=", A
import two
print "In one.py, after importing two, A=", A
--- end one.py

--- begin two.py ---
import one
print "In two.py, one.A=", one.A
one.A = 222
print "In two.py, after modifying one.A=", one.A
--- end one.py

Executing:
>python one.py
you get this output:

In one.py, A= 1
In two.py, one.A= 1
In two.py, after modifying one.A= 222
In one.py, after importing two, A= 1

In this (pathological) case, there are TWO different instances of the
one.py module, because modules are indexed by name in the sys.modules
dictionary, and the first instance is under the "__main__" name, and the
second instance is under the "one" name.
So: don't import the main script again.

--
Gabriel Genellina

Nov 14 '07 #5

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

Similar topics

2
1655
by: Chris S. | last post by:
Out of a somewhat academic interest, I've created a rudimentary module for persisting dynamically created objects and data structures in plain Python source code. Presently, it's a little under a thousand lines of code. It's still a work in progress and has several limitations but it is producing results. Is there any interest for me to clean it up and publicly release it?
2
3088
by: Citoyen du Monde | last post by:
Trying to get some ideas on a simple javascript project (to teach myself the language). I want to develop a client-side vocabulary practice application that would allow users to enter their own words, their own definitions plus an example of how the word is used in practice. It'll be all client side with - cookies? to get persistence so that the words won't disappear on me each time the page is closed (which is what happened when I
4
3620
by: Dave Veeneman | last post by:
When does serializing objects make more sense than persisting them to a database? I'm new to object serialization, and I'm trying to get a feel for when to use it. Here is an example: I'm writing an accounting application. I have a chart of accounts in the form of a containment hierarchy. A GeneralLedger contains a number of Accounts, and each of these Accounts can contain a Aubledger, which contains its own Accounts, and so on. The...
1
1669
by: lim | last post by:
What is the possible error that occurs when the Page_load event is not triggered during execution. In my page there's some basic server control. Is there any loops holes?
1
1810
by: Larry Bird | last post by:
I've created a AlertDataClass below within the class I have tables and column that I've create. In the AlertDataAccess class I'm trying to insert data into my tables. AlertDataAccess is a Module that is trying to insert data into the tables. Within the AlertDataClass is subroutine that init and creates ColumnNames. In invoke the AddDataColumnNames() sub to create the column headers. Why can't I see the column names in my module that I'm...
2
3277
by: xenophon | last post by:
I added a Hidden Form Field to a form in the code behind. The value is being set in JavaScript client-side, but it is not persisting to the server in the PostBack. I know the value is being set properly because it displays in the document.write method. Create a simple page and paste the below in the code-behind (ASP.NET 1.1-SP1) using System;
5
4837
by: Dick | last post by:
I have a GridView bound to an ObjectDataSource. I have a Button that calls GridView.DataBind. I want the row that is selected before the DataBind to still be selected afterwards. This happens automatically if the data doesn't change. But if records have been added or deleted then it looks as if some code is necessary: I've done this by using GridView.SelectedValue to get the key value of the currently selected Row and then by itterating...
18
2752
by: Joel Hedlund | last post by:
Hi! The question of type checking/enforcing has bothered me for a while, and since this newsgroup has a wealth of competence subscribed to it, I figured this would be a great way of learning from the experts. I feel there's a tradeoff between clear, easily readdable and extensible code on one side, and safe code providing early errors and useful tracebacks on the other. I want both! How do you guys do it? What's the pythonic way? Are...
1
3601
by: Nikron | last post by:
Hi, I'm having an issue with the ASP.NET 2.0 Treeview control and persisting its' state accross requests. My Control is embedded within a master page and is used for site navigation. My problem is that the user wants to know which page they are currently on and therefore I need to highlight the selected node. The problem is I lose state whenever the user selects a node and is redirected to another page. Thanks in advance
0
8946
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
9447
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
9307
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
9235
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
9181
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
6735
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...
1
3261
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
2721
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2180
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.