Compiling Python code within a module
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Sat May 19 03:11:59 EDT 2007
En Fri, 18 May 2007 20:49:33 -0300, Mitko Haralanov <mitko at qlogic.com>
escribió:
> On 18 May 2007 15:51:40 -0700
> ici <iltchevi at gmail.com> wrote:
>
>> exec it :)
>
> Thank you! That works when I compile/exec it in the main body of the
> program. However, when I try to do that in a separate module it
> doesn't. For example:
exec has a long form - see http://docs.python.org/ref/exec.html
And forget the compile pass - let Python handle it automatically. Also
note that exec is a statement, not a function, so you don't need ()
To "inject" inside a module a function defined in source_code, do:
exec source_code in module.__dict__
To "inject" a function inside a class, it's easier if you use an
intermediate dictionary:
d = globals().copy()
exec source_code in d
my_class.method = d['method']
> def register (self, text):
> exec (compiler.compile (text, "<string>",
> "exec"))
>
> f.register ("def blah():\n\tprint 'blah'\n")
>
> In this case, the function 'blah' is nowhere to be found. I've tried
> looking in 'f', in the class 'Foo', in the module 'Foo' and it's
> nowhere.
It existed briefly in the local namespace of the register method - after
register is exited, it's gone.
--
Gabriel Genellina
More information about the Python-list
mailing list