[Python-ideas] Allowing def to assign to anything

Ryan Gonzalez rymg19 at gmail.com
Mon Oct 26 10:30:12 EDT 2015


You can just do:

dispatch = {}
def dispatcher(f):
    dispatch[f.__name__] = f

@dispatcher
def foo(bar):
    return bar * bar


I really think that might be weird and kind of jarring to read...

On October 26, 2015 1:02:00 AM CDT, Alexander Walters <tritium-list at sdamon.com> wrote:
>In my code, I write a lot of dispatch dictionaries (for lack of a
>switch 
>statement, but I will not hold my breath for that).  In trying to make 
>writing these dictionaries less annoying, I tend to use many lambdas. 
>I 
>can let you guess at what problems that has resulted in.  Of course,
>the 
>preferred way to write such dictionaries is by using a regular
>function, 
>and adding that function to a dictionary.  This isn't exactly a problem
>
>- it works, and works well, but it is annoying to write, and leaves 
>artifacts of those functions in module scope.  I propose a little bit
>of 
>sugar to make this a little less annoying.
>
>If `def` is allowed to assign to anything (anything that is legal at
>the 
>left hand side of an = in that scope), annoying artifacts go away.  The
>
>syntax I propose should be backwards compatible.
>
>```
>dispatch = {}
>
>def dispatch['foo'](bar):
>     return bar * bar
>```
>
>Does this make anything possible that is impossible now?  No.  But it 
>does make the intent of the module author clear - the function is only 
>ever intended to live inside that dict, or list, or other structure.  
>This, to me, is less annoying to write, and is more readable.  This 
>obviously could be used outside of creating dispatch dictionaries, but 
>that is the use case I would benefit from.
>_______________________________________________
>Python-ideas mailing list
>Python-ideas at python.org
>https://mail.python.org/mailman/listinfo/python-ideas
>Code of Conduct: http://python.org/psf/codeofconduct/

-- 
Sent from my Nexus 5 with K-9 Mail. Please excuse my brevity.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151026/191718b3/attachment.html>


More information about the Python-ideas mailing list