Function to import module to namespace

bvdp bob at mellowood.ca
Sun Jun 29 21:45:32 EDT 2008


John Machin wrote:

<snip>

Good questions. Short answer ... probably 'cause I've not thought the 
problem though completely :)

 > You are updating with *everything* in the 'more' module, not just the
 > functions. This includes such things as __name__, __doc__, __file__.
 > Could have interesting side-effects.
 >
 > One quick silly question: why do you want to do this anyway?
 >

I'm writing a "simple" macro expander. I've got some mainline code which 
reads an input file, parses out macros, and expands them. So, in my 
input file I might have something like:

      a fjas j kj sdklj sdkl jfsdkl [ link somewhere sometext ]

So, I need a function link() to evaluate and return "http://...."

Instead of putting funcs like link() in my mainline I've stuck them in a 
module of their own. In the mainline I

    import funcs

and then when I need to expand I have the following code:

if not cmd in vars(funcs):
         error("Unknown function/variable '%s'" % cmd)

     if type(vars(funcs)[cmd]) == type(parse):
         txt = eval("""funcs.%s("%s")""" % (cmd, arg))

     else:   # not a func, just expand the variable
         if arg:
             error("Argument to variable '%s' not permitted." % cmd)
         txt = str(eval("funcs.%s" % cmd ))

Of course, the question comes up ... what if a user (probably me) wants 
to add more functions? Easy enough to just edit funcs.py I suppose, but 
I thought it'd be nice to use more modules.

So, I suppose that rather than adding the 2ndary module stuff to the 
default 'funcs.py' I could just as well have a look and check for the 
needed function in all the modules I've imported.


> Sorry, *two* quick silly questions: are the add-on modules under your
> control, or do you want to be able to do this with arbitrary modules?
> [If under your control, you could insist that such modules had an
> __all__ attribute with appropriate contents]

Why would I want to do that ... and how?

> A third: why do you want to import into an existing namespace? Now
> that you know about __import__, why just not call the functions where
> they are?

Yeah, that would probably be cleaner (safer).

Thanks.



More information about the Python-list mailing list