[Python-ideas] Allowing def to assign to anything

Alexander Walters tritium-list at sdamon.com
Mon Oct 26 02:30:28 EDT 2015



On 10/26/2015 02:20, Chris Angelico wrote:
> I agree; the idea has been raised a few times, and I think it'd be
> helpful. It's probably not necessary to allow the _entire_ scope of
> "anything legal on the left of =", as that's pretty broad; even if the
> only form allowed were obj[key], it'd be useful.

I agree, that perhaps the scope could be a little wide when put this 
way, but my instinct is that 'allow anything already legal for =' would 
be the path of least frustration when implementing this.  I could be 
woefully wrong.  I do at least wish to assign to object with __setitem__ 
defined.

>
> But for building a dispatch dictionary, you could simply decorate your
> functions with a capturer:
>
> dispatch = {}
>
> def cmd(func):
>      dispatch[func.__name__] = func
>      return func
>
> @cmd
> def foo(bar):
>      return bar * bar
>
> You can even merge the decorator and the dict itself:
>
> class DispatchDict(dict):
>      def __call__(self, func):
>          self[func.__name__] = func
>          return func
>
> dispatch = DispatchDict()
>
> @dispatch
> def foo(bar):
>      return bar * bar
>
> This does require that your dict keys be legal identifiers (you can't
> do "def dispatch['!'](x):" as "@cmd def !(x)"), but for a lot of
> common cases, this does work. I've used this style for building
> argparse UIs and such, and it's a lot easier than most other options
> I've played with.

This does, indeed, make life a bit easier in the here and now (and is 
similar to kitbashed techniques I already use).  I am hoping to make 
that obsolete.

>
> ChrisA
> _______________________________________________
> 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/
- Alex


More information about the Python-ideas mailing list