adding methods on the fly

Alex Martelli aleax at aleax.it
Wed Jul 10 10:17:25 EDT 2002


Renzo Tomaselli wrote:
        ...
>> You can marshal such objects to bytestrings, too, for storing as BLOBs
>> or whatever.
> 
> Yuup! this was the big missing point. Indeed I need to marshal all
> functions (user-defined methods, actually) down to my OODBMS (and the

Slightly imprecise of me -- you can't marshal.dumps the function
object f itself; rather you marshal its f.func_code (then rebuild
a function object from the unmarshaled code with new.function):

>>> def f(): print 'ciao!'
...
>>> maco = marshal.dumps(f.func_code)
>>> # save and later reload bytestring maco at will
>>> newf = new.function(marshal.loads(maco), {})
>>> newf()
ciao!
>>>

Globals and argument defaults too if you need them, of course.

The function becomes a method later (via new.instancemethod or
otherwise).


>> > I still wonder why it's so hard (from a C/C++ perspective) to walk
>> > from a "def foo(self): pass" string to a callable object to be added
>> > to a class.
>> But it's not.  exec that with a locals dictionary, and in the dictionary
>> at key 'foo' you find exactly a Python callable object (a function
>> object, to be precise).  What IS "so hard" about this?  def is an
>> executable statement, used to create function objects, so, if you
>> start with a def statement and want a function object, you, of course,
>> execute the statement.  What COULD possibly be easier or mote natural?
> 
> True but not obvious. I spent days in searching through this list on
> Google (and on C++ SIG as well). There are many messages about
> extending/embedding but none came to the above conclusions when the
> target is focused on methods.

Right.  The "focus on methods" may be the misleading part, given that
the Python-coded function becomes a method object separately from all
the rest of the operation -- just a hypothesis on why things may not
have been said in this particular context earlier!


> Thank you very much Alex, let me know if you plan to visit this area
> in the near future.

I'm vacationing in Trentino-Alto Adige around Ferragosto, but near
the Lago di Carezza, not in Valsugana this year!-)


Alex




More information about the Python-list mailing list