[Python-ideas] Allowing def to assign to anything

Andrew Barnert abarnert at yahoo.com
Mon Oct 26 23:48:11 EDT 2015


On Oct 26, 2015, at 19:48, Chris Angelico <rosuav at gmail.com> wrote:
> 
> On Mon, Oct 26, 2015 at 6:05 PM, Andrew Barnert via Python-ideas
> <python-ideas at python.org> wrote:
>> On Oct 25, 2015, at 23:23, Alexander Walters <tritium-list at sdamon.com> wrote:
>>> 
>>> I imagine in the case of assigning to a class or instance, the name would be the same (and binding to self would act the same) as if it were assigned in the traditional way.
>> 
>> In what traditional way? When you def a function, its name is the name given in the def statement. If you later assign it to a member of an object, that doesn't change its name. So, that doesn't answer the question.
>> 
> 
> dispatch = {}
> def dispatch['foo'](): pass
> assert dispatch['foo'].__name__ == "dispatch['foo']"
> 
> I have no problem with this, conceptually.

The paragraph you're replying to was about the naming for "def foo.bar():", which Alexander had suggested would work differently from "def foo['bar']():" (which he later retracted). So I'm not sure why you're proposing a different alternative for "def foo['bar']():" in response to these paragraphs.

At any rate, later in the thread, Alexander suggested something like "<anon: dispatch['foo']>", which I like better. The angle brackets and "anon" tell you that it's not guaranteed to be a REPL-friendly name—which would be possible in this case, but not in general. Plus, the part after the "anon" is just the text of the target node, so it's dead simple. (And if you're worried that this means the function's repr ends up with nested angle brackets—well, it does, but the same is true for lambda functions, and the hidden functions on comprehensions.)

> Syntactically, it would be
> defined as f"dispatch[{key!r}]" if the key is allowed to be an
> arbitrary expression.

But surely dispatch is also allowed to be an arbitrary expression? And, similarly, foo in foo.bar? And in those cases, the repr of those parts is worse than useless (you'd get the contents of dispatch instead of its name), so there's really no alternative.

Also, your suggestion means that this will assert:

    dispatch = {}
    def dispatch["foo"](): pass
assert dispatch['foo'].__name__ == 'dispatch["foo"]'

… will assert, so it's a pretty weak DWIM anyway.

Alexander's solution doesn't have any of those problems.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151026/3705f756/attachment-0001.html>


More information about the Python-ideas mailing list