[Python-Dev] Those import related syntax errors again...

Guido van Rossum guido@digicool.com
Wed, 21 Feb 2001 21:07:49 -0500

> [Guido]
> > I don't understand.  Methods do have a function declaration:
> >
> >   class C:
> >
> >       def meth(self):
> >           pass
> >
> > Or am I misunderstanding?

> The problem is I have a class object, and the source-code for the method
> body as a string, generated at runtime based on runtime info from the
> reflection capabilities of the system we are interfacing to.  The simplest
> example is for method code of "return None".
> I dont know how to get a code object for this snippet so I can use the new
> module to get a new method object.  Attempting to compile this string gives
> a syntax error.  There was some discussion a few years ago that adding
> "function" as a "compile type" may be an option, but I never progressed it.
> So my solution is to create a larger string that includes the method
> declaration, like:
> """def foo(self):
>       return None
> """
> exec that, get the function object out of the exec'd namespace and inject it
> into the class.

Aha, I see.  That's how I would have done it too.  I admit that it's
attractive to exec this in the local namespace and then simply use the
local variable 'foo', but that doesn't quite work, so 'exec...in...'
is the right thing to do anyway.

--Guido van Rossum (home page: http://www.python.org/~guido/)