473,396 Members | 2,076 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,396 software developers and data experts.

namespace & imported modules

Hi,

I've been having trouble understanding the difference between global
namespace within and between modules. For example, I can program a
subthread to see a global name (a threaded event to be specific);
however, somehow when I break up my code into different modules, the
subthread can no longer see the global name in the main program.

Here's an example of what I'm trying to accomplish:

Working script pseudo-code:
================================================== ====
# main.py
---------------------------
import std modules

def thread1
def thread2

launch thread1: wait for event
launch thread2: signal thread1's event
================================================== ====
#END: Broken script pseudo-code

and here's it's seemingly equivalent part...

#START: Broken script pseudo-code
================================================== ====
# subfile.py:
---------------------------
import std modules

def thread1
def thread2

---------------------------
# main.py
import std modules
from subfile import thread1, thread2 # this should be the only
difference

launch thread1: wait for event
launch thread2: signal thread1's event
================================================== ====
#END: Broken script pseudo-code

The broken code would yield the following exception when thread2 tries
to signal thread1's event:
"NameError: global name 'myName' is not defined"

I hope I didn't simplify the problem too much, but I didn't want to
paste 200 lines of code for no one to read.

Obviously I'm missing something regarding namespace and global scopes.
Would anyone be able to point out what I've overlooked? Any help is
appreciated.

-Jason
Jul 18 '05 #1
3 1378
Jason wrote:
I've been having trouble understanding the difference between global
namespace within and between modules. For example, I can program a
Did you know that global variables are only global to the module?
from subfile import thread1, thread2 # this should be the only


This will bind the names thread1 and thread2 in the importing module, i. e.
you have now two distinct thread1 variables no longer pointing to the same
object after a thread1 = something assignment in one of the modules. Do

import subfile

instead and access the variables with qualified names

subfile.thread1 = something

in all modules except subfile.py, and everything should be OK.

Peter

Jul 18 '05 #2
Thanks for your quick reply, Peter.

I had to dust off my Learning Python book, which I had read cover to
cover many months ago. After re-reading some key sections I now
understand what 'global' scope really means and why you suggested
importing the module directly, rather than copying the namespace with
the 'from' statement.

When importing the module directly as 'import module' in lieu of 'from
module import *', this doesn't seem to address the issue I'm having.

My main program now imports the submodule names that must be qualified
with the module name, but the function in one submodule still can't
see the function (class instance method to be exact) defined in the
other submodule.

I suppose I can post the test code I was using. The multithreaded
hierarchy mimics that of my 'real' program that I need to integrate my
code into, so don't let this complexity confuse you.

================================================== =========
# main.py
#
#!/usr/bin/env python
#
# A customized class to terminate a thread using the threading
module's event-
# based functionality.
#
################################################## #############################

import threading, time

from hb_imports import *
import hb_imports
import hb_global

def main():
# launch WatchDog timer thread
bcast_watchdog = hb_global.WatchDog(timeout=3)
bcast_watchdog.setDaemon(1)
bcast_watchdog.start()

# launch global arbiter
glob_arbiter = threading.Thread(target=hb_global.global_arbiter)
glob_arbiter.setDaemon(1)
glob_arbiter.start()

time.sleep(7)
cfg['ISROOT'] = False # simulation: no longer root again

time.sleep(7)

if __name__ == '__main__':
main()

================================================== =========
# hb_global.py

import threading, time
import hb_stethoscope
from hb_imports import *

class WatchDog(threading.Thread):
def __init__(self, name='WatchDog', timeout=1.0):
self._timerevent = threading.Event() # assign event to instance
self._waitperiod = timeout # assign timeout delay to instance
variable

threading.Thread.__init__(self, name=name)

def run(self):
while 1:
while not cfg['ISROOT']:
print now() + 'Timer started. %s seconds to receive ping.' %
self._waitperiod

# initialize timer and flags
self._timerevent.clear() # BE KIND. REWIND.
self._intervened = False # init flag denoting intervention
occurred

# wait for reset() method to be called or timeout
self._timerevent.wait(self._waitperiod)

# if _intervened flag not set AND still not a root server (status
could change in countdown)
if not self._intervened and not cfg['ISROOT']:
print now() + "No broadcasts received in %s seconds! Becoming a
root server." % (self._waitperiod,)
cfg['ISROOT'] = True # modify root status

time.sleep(0.1) # sleep 100ms to avoid constant polling

def reset(self):
self._intervened = True
self._timerevent.set()
def global_arbiter():
threading.Thread(target=hb_stethoscope.stethoscope ).start()

================================================== =========
# hb_stethoscope.py

import threading, time
import hb_global
from hb_imports import *

def stethoscope():
for i in range(6):
if i == 3:
time.sleep(4)
sim_delay = 1
time.sleep(sim_delay)
threading.Thread(target=bcast_handle).start()

def bcast_handle():
print now() + 'Receiving broadcast ping. Reseting watchdog timer.'
hb_global.bcast_watchdog.reset()

================================================== =========
# hb_imports.py

import time

otime = time.time()

def now():
ctime = time.time()
return '%.2f :: ' % (ctime-otime,)

cfg = dict()
cfg['ISROOT'] = False

================================================== =========

The last line in hb_stethoscope.py, hb_global.bcast_watchdog.reset(),
is _supposed_ to call the WatchDog.reset() class instance method in
hb_global.py.

I've been very frustrated trying to find out why I can't access this
method.

Thanks for anyone taking a look at this problem.

Happy Thanksgiving,

Jason
Jul 18 '05 #3
Jason wrote:
def main():
# launch WatchDog timer thread
bcast_watchdog = hb_global.WatchDog(timeout=3)
[...]
The last line in hb_stethoscope.py, hb_global.bcast_watchdog.reset(),
is _supposed_ to call the WatchDog.reset() class instance method in
hb_global.py.


It seems you are creating bcast_watchdog as a local variable in
__main__.main(). How would you suppose it to become magically inserted in
the hb_global namespace? Do

def main():
bcast_watchdog = hb_global.WatchDog(timeout=3)
hb_global.bcast_watchdog = bcast_watchdog

to insert the WatchDog instance into the hb_global module. (Note that there
may be other problems as I didn't look any further)

Peter
Jul 18 '05 #4

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

Similar topics

3
by: Tonguç Yumruk | last post by:
I'm trying to build a completely plug-in based system. One of my problems is importing a package dynamically. I'm trying to emulate the import command. The __import__() function or imp module...
5
by: Blair Hall | last post by:
Can anyone please tell me how to correctly use a built in function when there is a function of the same name in local scope? Here is an example. Suppose the following is in myApply.py: def...
2
by: Fritz Bosch | last post by:
Hi experts Is is possible to import/manipulate a module such that I can supply its __dict__? I want to supply my own dict subclass object to be filled by the import, e.g. a class like: >>>...
0
by: robert | last post by:
As more and more python packages are starting to use the bloomy (Java-ish) 'logging' module in a mood of responsibility and as I am not overly happy with the current "thickener" style of usage, I...
2
by: Kiran | last post by:
Hello All, I am kind of a beginner to python, but here is the deal. I am writing a wxpython Application, in which I have a GUI. This GUI imports some other modules that I have written, using...
30
by: Pep | last post by:
Is it best to include the code "using namespace std;" in the source or should each keyword in the std namespace be qualified by the namespace tag, such as std::cout << "using std namespace" <<...
5
by: Steven W. Orr | last post by:
I have two seperate modules doing factory stuff which each have the similar function2: In the ds101 module, def DS101CLASS(mname,data): cname = mname+'DS101' msg_class = globals() msg =...
0
by: Gabriel Genellina | last post by:
En Sat, 24 May 2008 08:57:37 -0300, ohad frand <ohad911@gmail.comescribió: If you want Python to forget about module tmp1: del sys.modules But most of the issues with reload apply too...
4
by: bvdp | last post by:
Terry Reedy wrote: <snip> <snip> <snip>
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...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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,...
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...

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.