Dynamic/runtime code introspection/compilation

T

Thomas W

Maybe a stupid subject, but this is what I want to do :

I got some python code stored in a string:

somecode = """

from somemodule import ISomeInterface

class Foo(ISomeInterface):
param1 = ...
param2 = ....

"""

and I want to compile that code so that I can use the Foo-class and
check what class it extends, in this case ISomeInterface etc. I've
tried eval, codeop etc. but it doesn't work. Something like this would
be nice :

from somemodule import ISomeInteface

d = compile(sourcecode)

myfoo = d.Foo()

print ISomeInterface in myfoo.__bases__

Any hints?
 
F

Fredrik Lundh

Thomas said:
from somemodule import ISomeInteface

d = compile(sourcecode)

myfoo = d.Foo()

print ISomeInterface in myfoo.__bases__

Any hints?

Python is a dynamic language, so compiling something won't tell you much
about what the code actually does. the only reliable way to do that is
to execute the code:

code = compile(sourcecode)
namespace = {}
exec code in namespace
print issubclass(namespace["Foo"])

</F>
 
L

Leo Kislov

Thomas said:
Maybe a stupid subject, but this is what I want to do :

I got some python code stored in a string:

somecode = """

from somemodule import ISomeInterface

class Foo(ISomeInterface):
param1 = ...
param2 = ....

"""

and I want to compile that code so that I can use the Foo-class and
check what class it extends, in this case ISomeInterface etc. I've
tried eval, codeop etc. but it doesn't work. Something like this would
be nice :

from somemodule import ISomeInteface

d = compile(sourcecode)

myfoo = d.Foo()

print ISomeInterface in myfoo.__bases__

Any hints?

Here is hello world program for plugins:

import sys

somecode = """
class Foo:
param1 = "Hello, world!"
"""

plugin = type(sys)('unknown_plugin') # Create new empty module
exec somecode in plugin.__dict__

print plugin.Foo.param1

-- Leo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top