Alternative to multi-line lambdas: Assign-anywhere def statements

Devin Jeanpierre jeanpierreda at gmail.com
Sat Jan 24 23:36:22 EST 2015


On Sat, Jan 24, 2015 at 5:58 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
> On 01/24/2015 11:55 AM, Chris Angelico wrote:
>> On Sun, Jan 25, 2015 at 5:56 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
>>> If the non-generic is what you're concerned about:
>>>
>>> # not tested
>>> dispatch_table_a = {}
>>> dispatch_table_b = {}
>>> dispatch_table_c = {}
>>>
>>> class dispatch:
>>>   def __init__(self, dispatch_table):
>>>     self.dispatch = dispatch_table
>>>   def __call__(self, func):
>>>     self.dispatch[func.__name__] = func
>>>     return func
>>>
>>> @dispatch(dispatch_table_a)
>>> def foo(...):
>>>    pass
>>
>> That's still only able to assign to a key of a dictionary, using the
>> function name.
>
> This is a Good Thing.  The def statement populates a few items, __name__ being one of them.  One of the reasons lambda
> is not encouraged is because its name is always '<lambda>', which just ain't helpful when the smelly becomes air borne!  ;)

Actually, in this case you'd probably want the function's __name__ to
be something different, since it'd be confusing if all three dispatch
tables had a 'foo' entry, using functions whose name was 'foo'.

No reason a function's name can't be "dispatch_table_a['foo']"

-- Devin



More information about the Python-list mailing list