packages, globals, and __builtin__

Ben Hutchings ben.hutchings at roundpoint.com
Fri May 11 18:26:52 EDT 2001


Laura Creighton <lac at cd.chalmers.se> writes:

> Okay, consensus is that I should use a module name inside the package.
> Confession time.  I am already doing this.  I've already GOT one, you see.
<snip>
> Is it my __init.py__ file that is no good? This is Caps/Widgets/__init.py__
> 
> 	import os
> 	import re
> 
> 	dir = __path__[0]
> 	for _file in os.listdir(_dir):
> 	    if _file != '__init__.py':
> 	        _m = re.match('(.*)\.py$', _file)
>         	if _m != None:
> 	            exec('from ' + _m.group(1) + ' import *')
> 
> Some day I want to make it do lazy loading, but now now.
> 
> What have I badly misunderstood?

You've misunderstood how package and module namespaces work.

The package namespace contains names of all modules within the
package that have been imported, plus any names bound in its
initialisation code (__init__.py).

Names bound in the package namespace are not bound in module
namespaces.  You have to explicitly import them in the individual
modules.

You should probably bind the preferences to a name in the package
namespace, then import Caps.Widgets in client code and in individual
modules.  It's probably a bad idea to import the name of the
preferences (e.g. "from Caps.Widgets import prefs") because if the
name is rebound in Caps.Widgets it won't be rebound in the modules.

It would be safer to define setPrefs() and getPrefs() functions for
this purpose.  You can then safely import the function names into
module namespaces.

-- 
Any opinions expressed are my own and not necessarily those of Roundpoint.



More information about the Python-list mailing list