473,700 Members | 2,899 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1393
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.Watch Dog(timeout=3)
bcast_watchdog. setDaemon(1)
bcast_watchdog. start()

# launch global arbiter
glob_arbiter = threading.Threa d(target=hb_glo bal.global_arbi ter)
glob_arbiter.se tDaemon(1)
glob_arbiter.st art()

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(thread ing.Thread):
def __init__(self, name='WatchDog' , timeout=1.0):
self._timereven t = threading.Event () # assign event to instance
self._waitperio d = timeout # assign timeout delay to instance
variable

threading.Threa d.__init__(self , name=name)

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

# initialize timer and flags
self._timereven t.clear() # BE KIND. REWIND.
self._intervene d = False # init flag denoting intervention
occurred

# wait for reset() method to be called or timeout
self._timereven t.wait(self._wa itperiod)

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

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

def reset(self):
self._intervene d = True
self._timereven t.set()
def global_arbiter( ):
threading.Threa d(target=hb_ste thoscope.stetho scope).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.Threa d(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.Watch Dog(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.Watch Dog(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
7651
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 doesn't help me much because they only return the module. I want to register the module with it's name in the current namespace. I can do it by: globals() = __import__(module_name) But I don't think it's a good thing to access the global namespace...
5
1964
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 apply(func,seq): # # Code can default to # built-in definition in some cases: return __builtins__.apply(func,seq)
2
1954
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: >>> class MyModuleDict(dict): .... def __setitem__(self,name,val):
0
1861
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 want to put this comment and a alternative most simple default framework for discussion. Maybe there are more Python users which like to see that imported (managed) logging issue more down-to-earth and flexible ? ... Vinay Sajip wrote: >...
2
1040
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 the format import mymodule as _MyModule Now, this GUI in addition to having all it's bells and whistles has a console (from pyshell), so that the user can run their own scripts inside this GUI.
30
4108
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" << std::endl; Myself I am not sure which I prefer, it is certainly easier to specify that the std namespace is being used instead of tagging each member of the namespace?
5
1290
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 = msg_class(data) return msg
0
144
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 http://docs.python.org/lib/built-in-funcs.html#l2h-61 See http://docs.python.org/ref/import.html to see how the import statement works, and PEP 328 http://docs.python.org/whatsnew/pep-328.html to see how using relative imports can help in this case, but...
4
1243
by: bvdp | last post by:
Terry Reedy wrote: <snip> <snip> <snip>
0
9202
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
9058
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
8952
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
8909
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
6555
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
5894
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
4395
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
3081
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
3
2018
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.