Newbie Question. Class definitions on the fly.

Simon Forman rogue_pedro at yahoo.com
Mon Aug 28 00:29:14 EDT 2006


ishtar2020 wrote:
> Hi everyone
>
> I'm sure this question is kinda stupid and has been answered a few
> times before... but I need your help!
>
>  I'm writing a small application where the user can analyze some text
> based on a set of changing conditions , and right now I'm stuck on a
> point where I'd like to automatically generate new classes that operate
> based on those user-defined conditions.
>
> Is there a way in python to define a class in runtime? For instance,
> can I define a class which extends another(that I have previously
> defined in some module) , create some instance completely on the fly
> and then add/redefine methods to it?
>
> If affirmative, I've thought of a problem I would maybe have to face:
> as the class has been defined by direct input to the python
> interpreter, I could only create instances of it on the same session I
> entered the definition(because it's not on a module I can load on
> future uses) but not afterwards.  Is there a way to keep that code?
>
> Even more newbie paranoia: what would happen if I make that 'on the
> fly" object persist via pickle? Where would Python find the code to
> handle it once unpickled on another session (once again, i take that no
> code with the definition of that instance would exist, as it was never
> stored on a module).
>
> Hope it wasn't too ridiculous an idea.
>
> Thank you for your time, guys.

It's not ridiculous at all.  The easiest way to do what you want would
be to build a string containing your new class and then run it with the
exec statement:

|>> s = 'class foo: pass'
|>> exec s
|>> foo
<class __main__.foo at 0xb7defe9c>

If you want to keep your new class around between runs of your script
(and if you want to make it pickle-able) then you should write your
strings to a .py file (be sure to include an import statement to import
the classes you're subclassing) and import that file.

If you do that and are going to modify the class(es) during a single
session, be sure to call reload() on your new (modified) file (rather
than just importing it again) otherwise you won't get the changes.

See http://docs.python.org/ref/exec.html for the exec statement and
http://docs.python.org/lib/built-in-funcs.html#l2h-59 for the reload()
function.

Peace,
~Simon




More information about the Python-list mailing list