interesting Namespace problem

Stephen news at myNOSPAM.org
Thu Apr 19 07:27:43 EDT 2001


    The first way to do this that pops into my mind is the following. It
will execute the import statement in the global namespace. This seems
inherantly evil, There's got to be a better approach to what you're doing
this for. Heh. Maybe its just because I find 'exec' to be strangely evil all
on its own.

def import_module(module):
    exec "import %s" % module in globals()
    do_stuff("print os.sep")

--Stephen
(replace NOSPAM with 'seraph' to respond in email)


"Duncan Booth" <duncan at NOSPAMrcp.co.uk> wrote in message
news:Xns908870BCC98BFduncanrcpcouk at 127.0.0.1...
> "Markus Gritsch" <gritsch at iue.tuwien.ac.at> wrote in <9bmb56$gjs$1
> @news.tuwien.ac.at>:
>
> > And here the problem arises: The name os is not known in do_stuff().  Is
> > there a way to make the namespace of import_module() available in
> > do_stuff()?
> >
>
> def do_stuff(stuff, v):
>     exec stuff in v
>
> def import_module(module):
>     v = {}
>     exec 'import ' + module in v
>     do_stuff('print os.sep', v)
>
> import_module('os')
>
>
> --
> Duncan Booth
> duncan at dales.rmplc.co.uk
> int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
> "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?





More information about the Python-list mailing list