How to get two modules loaded into the same namespace?

Emile van Sebille emile at fenx.com
Thu Nov 8 12:17:01 EST 2001


----- Original Message -----
From: <r.vanwees at chello.nl>
Newsgroups: comp.lang.python
Sent: Thursday, November 08, 2001 8:06 AM
Subject: How to get two modules loaded into the same namespace?


> I am trying to build a rule engine. I have two Python modules:
> RuleEngine.py and utilities.py.
>
> I want to keep the engine and the utility functions separated for
> reasons of maintainiability and cleannes.
>
> I am running into a few problems:
>
> 1) In RuleEngine.py I have defined a global, DEBUG_PRINT_LEVEL, which
> allows me to steer the amount of debug info I get at runtime
> (curently somewhere between 'nothing' and 'an awful lot').
>
> When I try the following in RuleEngine.py:
>
>     global DEBUG_PRINT_LEVEL
>     DEBUG_PRINT_LEVEL = 0
>     from utilities import *
>
>     class RuleEngine:
>         someUtilityFuncThatReferencesDEBUG_PRINT_LEVEL()
>
> I get a NameError on DEBUG_PRINT_LEVEL (see stack trace below):
>
>     File "D:\Dev\PyCharGen\utilities.py", line 120, in calcLevel
>     if DEBUG_PRINT_LEVEL >= 4:
>     NameError: global name 'DEBUG_PRINT_LEVEL' is not defined
>     Process terminated with exit code 0
>

The issue here is that 'DEBUG_PRINT_LEVEL'  is not available to calcLevel in
D:\Dev\PyCharGen\utilities.py.  global applies to the
module space, calcLevel lives in a different module, ie, your import *
hasn't moved the function, simply imported a refernce to it
into RuleEngine.py's globals.

You may consider setting up a parameters module or dict that both refer to
when testing DEBUG_PRINT_LEVEL.

> As far as I understand the
> docs, the 'from x import *' syntax should import stuff into the
> current namespace, but apparently this does not hold for globals.
>
> 2) Several functions in utilities.py refer back to functions in
> RuleEngine.py. They also return a NameError (see stacktrace below
> from an actual debug log)
>
>     File "D:\Dev\PyCharGen\utilities.py", line 157, in calcSpells
>     statLevel = find(stat, 'base') + find(stat, 'bonus')
>     NameError: global name 'find' is not defined
>     Process terminated with exit code 0
>
> Again, it seems that the two modules are not in the same namespace.
>

That's right.


> Both python 2.1.1 and 2.2beta show this behavior.
>
> Does anyone know a solution (other than putting the utility functions
> in RuleEngine.py) to this problem? I must admit that I got lost at
> the Python namespace rules before...
>

Stop doing from module import *.  Do import module, then refer to the
objects as module.obj using qualified names.  The errors
should stop.

HTH,


Emile van Sebille
emile at fenx.com

---------





More information about the Python-list mailing list