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

Ethan Furman ethan at stoneleaf.us
Sat Jan 24 13:56:17 EST 2015


On 01/23/2015 10:28 PM, Chris Angelico wrote:
> 
> cmd = {}
> def command(func):
>     cmd[func.__name__] = func
>     return func
> 
> @command
> def foo(*args):
>     print("You asked to foo.")
> 
> but this is hardly generic. There's no convenient way to give an
> argument to a decorator that says "please assign this here", short of
> using some stupid eval hack... is there?

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

--
~Ethan~

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20150124/bd4af03b/attachment.sig>


More information about the Python-list mailing list