[Python-ideas] Allowing def to assign to anything

Andrew Barnert abarnert at yahoo.com
Mon Oct 26 03:55:18 EDT 2015


On Oct 26, 2015, at 00:09, Alexander Walters <tritium-list at sdamon.com> wrote:
> 
> to be clear, I propose the following to be equivalent (to clear up what I mean)

Yes, that clears it up. This is what I thought you probably wanted. But I think it would be better to keep it simpler. Instead of this:

> # classes:
> 
> class Foo:
>    def bar(self):
>        pass

… your first example would be simpler if it were equivalent to this:

class Foo:
    pass
def _dummy(self):
    pass
Foo.bar = _dummy

(except of course not binding anything to "_dummy").

Notice that this is now exactly like your second example, with an instance, so we only need one rule instead of two. And in simple cases it does exactly what you want here, too. And in complex cases, e.g., involving "__class__" or no-argument "super" or names accessible in the class-definition scope, the implementation doesn't need to do any magic, while with your version, it would. (That magic might be convenient in some cases, but since you don't want to encourage this kind of use anyway, why make things more complicated just to make the discouraged use more convenient?)

In fact, I would make this as simple as possible: Just change the "funcname" in the syntax from an identifier to a target. Then, any "def" statement whose works by defining a function, then assigning it to the target (which is legal iff the target is a legal assignment target). It's a perfectly normal assignment, following all the same __setitem__, __setattr__, descriptor, etc. rules as any other assignment.

That does mean the name of the function ends up being "Foo.bar" or "foo.bar" or "foo['bar']", and at least for the first two could end up being confusing, and even more so for the qualname, so maybe you'd want to add one minor tweak: if the target is not an identifier, the name is just "<none>" or "<anon>" or something. But I don't think you want to go any farther. (In particular, making any of the examples come out as "bar" is just extra complexity that only improves uses you don't want to encourage.)



More information about the Python-ideas mailing list