[Tutor] Dynamically naming functions
Kent Johnson
kent37 at tds.net
Mon Mar 13 15:08:06 CET 2006
Ed Singleton wrote:
> On 13/03/06, Kent Johnson <kent37 at tds.net> wrote:
> I've just discovered with a little playing, that you can do:
>
>
>>>>def z(v):
>
> ... def f(x):
> ... print x * v
> ... return f
> ...
>
>>>>c = z(3)
>>>>c(1)
>
> 3
>
>>>>funcdict = dict(foo = z(4))
>>>>funcdict["foo"](1)
>
> 4
>
> Which was obvious enough that I thought of trying it, but surprising
> enough that I was really pleased when it worked.
Yes, functions are first-class objects in Python. Functions can be
assigned to variable, passed to and returned from functions, stored in
lists and dictionaries...this is *very* useful in many contexts.
>>faces looks at foo.func_code.co_names to find the names you have used,
>>and it actually runs the function with a tracing hook to capture the values.
>>
>>There doesn't seem to be any other way to define a Task in faces,
>>either. You have to actually create functions. I guess this might be a
>>good place to use exec - just create the source code for the function
>>defs in a string and exec it, then retrieve the function from the global
>>namespace and pass it to faces. Then tell me why this API is better than
>>using nested dicts.
>
>
> Agreed, though to be fair the author of faces has probably
> overcomplicated the code for handling it (which is a damn shame as it
> is really quite a nice project planning tool). I guess you can't
> blindly iterate over the methods of functions, as there are other
> methods there that you might not want to use (like setattr and stuff,
> maybe?).
He may have overcomplicated it, but not by much. Offhand I couldn't even
think of how he might have done it, I had to look at the code. Python
has some ability to look at the details of a function - the attributes
of func_code - but to find out what value a local variable gets, you
have to call the function. These values aren't exposed outside the
function, that is why he uses the settrace() hook.
You might want to contact the author of faces and see what he suggests.
Maybe he would add an alternate method of creating Tasks and Projects.
Otherwise building and exec'ing a string is the only thing I can think
of. Yuck.
Kent
More information about the Tutor
mailing list