[Python-ideas] Allowing def to assign to anything

Terry Reedy tjreedy at udel.edu
Mon Oct 26 22:04:04 EDT 2015


On 10/26/2015 9:45 AM, Steven D'Aprano wrote:
> On Mon, Oct 26, 2015 at 02:02:00AM -0400, Alexander Walters 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.
>
> In this case, leaving "artifacts" in the module scope is a feature. If
> your function is simple enough to express in a simple expression, then a
> lambda may be the right solution. But if it requires a full block, then
> chances are that it's too complex for it to be obviously correct, which
> means you should test it. Giving the function a name and module scope
> supports testing.
>
> But if you really want to get rid of it:
>
> del the_function
>
> after adding it to the dispatch table.
>
> Or, stick them in their own namespace. For a package, that might mean
> moving the dispatch table and its associated functions into its own
> module. Or, put them in a class:
>
> class Switch:
>      def cheese(x):
>          ...
>      def spam(x):
>          ...
>      def eggs(x):
>          ...
>
> dispatch = {}
> dispatch.update(Switch.__dict__)

dispatch = dict(Switch.__dict__)

Except for the extraneous dunder names in __dict__, I like this.
For the fastidious,
dispatch = {k:v for k, v in Switch.__dict__.items() if k[0] != '_'}

This could be wrapped in a function that would take either a module 
(globals()) or class (.__dict__) as the namespace source.

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list