[Python-ideas] Allowing def to assign to anything

Chris Angelico rosuav at gmail.com
Mon Oct 26 22:20:20 EDT 2015


On Mon, Oct 26, 2015 at 5:30 PM, Alexander Walters
<tritium-list at sdamon.com> wrote:
>
>
> 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.

If you start by allowing only obj[key] (aka obj.__setitem__), and
maybe with only string literals or simple names for the key, it would
be a strict subset of Python syntax. That means that a future proposal
can easily expand on that (*un*like, for instance, the way
"{obj[key]}".format(obj=obj) operates), while providing only the one
or two most common usages:

def dispatch["foo"](x, y): pass

name = "bar"
def dispatch[name](x, y): pass


>> But for building a dispatch dictionary, you could simply decorate your
>> functions with a capturer:
>>
> 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.

Sure. You'll need some strong use-cases that justify _not_ using this
technique, though; since there's an existing way to do this, the bar
for new syntax is "show why the current way isn't good enough".

If you're worried about junk in your globals, what you could do is:

dispatch = {}
def cleanup():
    self = cleanup # we're going to delete ourselves, so snapshot to local
    for n,v in globals():
        if v is self: del globals()[n]

def cmd(func):
    dispatch[func.__name__] = func
    return cleanup

@cmd
def foo(): pass
@cmd
def bar(): pass

cleanup() # This function will self-destruct in three seconds. Two... one...


After all, a decorator can return anything it likes!

ChrisA


More information about the Python-ideas mailing list