dynamic function names
Michele Simionato
mis6 at pitt.edu
Mon Apr 28 08:46:26 EDT 2003
Alex Martelli <aleax at aleax.it> wrote in message news:<iP5ra.14084$3M4.382689 at news1.tin.it>...
> <posted & mailed>
>
> Bram Stolk wrote:
>
> > Hello,
> >
> > Is it possible in Python to define functions with a dynamic name?
>
> Yes, but not with the def statement.
>
>
> > something like:
> >
> > def make_func(funcname) :
> > def funcname :
>
> Syntax error -- you're missing parentheses here before the colon.
>
> > print "This func is named", funcname
> >
> > make_func(foo)
> > make_func(bar)
> >
> > The code above fails due to foo being unknown,
> > however, when calling as make_func("foo"), the "foo" string
> > cannot be used as a funcname.
>
> Actually, if you fix the syntax error it will work, but not do
> what you want:
>
> >>> def makefunc(funcname):
> ... def funcname(): print "this function is named", funcname
> ... return funcname
> ...
> >>> f = makefunc('foo')
> >>> f()
> this function is named <function funcname at 0x402c09cc>
> >>>
>
> See? "def funcname():" *RE-BINDS* identifier funcname to
> refer to the function object.
>
> So, what you need is to call function 'function' in module
> 'new'. You can first build a temporary function with a def
> to give you the right code, globals, defaults and closure,
> and then pass each of these to new.function together with
> the funcname you want to use:
>
> >>> import new
> >>> def makefunc(funcname):
> ... def temp(): print "this function is named", funcname
> ... f = new.function(temp.func_code, globals(), funcname,
> ... temp.func_defaults, temp.func_closure)
> ... return f
> ...
> >>> f = makefunc('foo')
> >>> f()
> this function is named foo
> >>> f.func_name
> 'foo'
> >>>
>
>
> Alex
In Python 2.3 most types are callable and one can often avoid the 'new'
module. In this example
new.function(temp.func_code, globals(), funcname,
temp.func_defaults, temp.func_closure)
could be replaced with
types.FunctionType(temp.func_code, globals(), funcname,
temp.func_defaults, temp.func_closure)
In addition to that, I have a question I always wanted to ask ;)
why I can change the name of a class (es. C.__name__='newC' works)
and I cannot change the name of a function (f.__name__='newf' does not
work) ?
More information about the Python-list
mailing list