Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #84490

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

Date 2015-01-24 20:35 +0000
From MRAB <python@mrabarnett.plus.com>
Subject Re: Alternative to multi-line lambdas: Assign-anywhere def statements
References <CAPTjJmrAQgtauH74dwCzb_-6T09D0dLVkxiGrAxJMp_OOwgS0g@mail.gmail.com> <54C3EAD1.2010501@stoneleaf.us> <CAPTjJmohdQbK9_ikh8heaMRbpJ270UW6C1AE2oNVgV_4AoYfQg@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.18097.1422131752.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 2015-01-24 19:55, Chris Angelico wrote:
> On Sun, Jan 25, 2015 at 5:56 AM, Ethan Furman <ethan@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. There's no way to represent fully arbitrary assignment
> in Python - normally, you can assign to a name, an attribute, a
> subscripted item, etc. (Augmented assignment is a different beast
> altogether, and doesn't really make sense with functions.) There's no
> easy way to say "@stash(dispatch_table_a['asdf'])" and have that end
> up assigning to exactly that.
>
Here's a slight variation on the theme:


class DispatchTable(dict):
     def __call__(self, name):
         def setter(func):
             self[name] = func
             return func
         return setter

command = DispatchTable()

@command("foo")
def _(*args):
     print("You asked to foo.")

@command("bar")
def _(*args):
     print("There's no wine in the bar.")

@command("asdf")
def _(*args):
     print("Asdf! Asdf!")

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Alternative to multi-line lambdas: Assign-anywhere def statements MRAB <python@mrabarnett.plus.com> - 2015-01-24 20:35 +0000

csiph-web