def <dynamic function name> () syntax ?

Alex Martelli aleaxit at yahoo.com
Thu Apr 5 04:32:56 EDT 2001


"Andrew Kuchling" <akuchlin at mems-exchange.org> wrote in message
news:3ditkkv9oo.fsf at ute.cnri.reston.va.us...
> "Bruce Edge" <bedge at troikanetworks.com> writes:
> > Can the follwoing be accomplished in Python?
> >
> > I want to create a func named "abc":
>
> Just bind the name to 'abc'.
> def dummy_name ():
>     ...
>
> abc = dummy_name
>
> Or: exec '%s = dummy_name' % name

Sure, but this has a flaw...:

>>> def dummy_name():
...     pass
...
>>> abc = dummy_name
>>> abc.func_name
'dummy_name'
>>>

i.e., the function internally retains the "dummy name".

One can work around this using module new, e.g.:

>>> import new
>>> if dummy_name.func_defaults is None:
...     abc = new.function(dummy_name.func_code, dummy_name.func_globals,
'abc')
... else:
...     abc = new.function(dummy_name.func_code, dummy_name.func_globals,
'abc',
...         dummy_name.func_defaults)
...
>>>


> But such dynamic creation of functions usually strikes me as a flawed
> design.  An informal rule of mine is that 'exec' or 'eval' should only
> be needed when you're expecting arbitrary expressions, perhaps in a
> config file, but exec'ing a single statement or applying eval() to a
> single name is usually a sign of programming in some non-Pythonic
> style.

Absolutely true!!!  And I suspect that 90%+ of the time this
also extends to usages of module new...


Alex






More information about the Python-list mailing list