Modules and Namespaces

Steve Holden steve at holdenweb.com
Thu Oct 20 12:10:57 EDT 2005


Jelle Feringa / EZCT Architecture & Design Research wrote:
> ##I'm sorry to stir up such a well discussed topic yet again, but namespaces
> are a point of confusion to me...
> 
> I took the effort of organizing my Python code (scripting a cad program
> calles Rhino) in well defined classes, which would be a terrific thing if I
> didn't got stuck in namespace issues.
> 
> I have a module that launches the application I'm scripting via win32com;
> rhino.load
> 
> from rhino import load
> RS = load.RS
> 
> So the application, with all its methods are now available through the RS
> (RhinoScript) object
> 
> from rhino import SRF # is where things get stuck
> 
> The RS object is the application scripted via COM, where all its method
> reside.
> In my module, SRF, I'm not importing anything, though it refers to the RS
> object all the time.
> Such as:
> 
> class srfBase:
>     '''Base class inherited by the srf* classes, binding general Rhino
> surface functionality to a particular
>     surface generation method'''
>     def __init__(self):
>         self.id   = 'self.id srfBase'
>         pass
>     def isBrep(self):
>         return RS.IsBrep(self.id)
>     def isPointInSurface(self, coord):
>         return RS.IsPointInSurface(self.id, coord)
> 
> 
> How do I make the RS object available to the imported SRF module, such that
> my module code and program code both refer to RS as the application object
> being scripted?
> 
One relatively simple way (though not a perfect solution) is to provide 
a function in the SRF module that allows the caller to provide a 
reference to the RS object, which is then stored as a module global. 
Similar to this:

# Somewhere in SRF's code

RS = None	# This RS is global to the SRF module

def RSreg(rs):
     global RS	# Ensures it isn't treated as function-local
     RS = rs

Then all you have to do is

from rhino import load
RS = load.RS

from rhino import SRF
SRF.RSreg(RS)

and everything inside SRF can refer to RS as a module global quite 
happily. Note that this falls over horribly if you ever want to handle 
several RS objects at the same time. In that case you might be better 
explicitly passing RS references into each function that uses them.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list