[Python-ideas] Allowing def to assign to anything

Alexander Walters tritium-list at sdamon.com
Mon Oct 26 04:01:22 EDT 2015


On 10/26/2015 03:55, Andrew Barnert wrote:
> … 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?)

Agreed, that is a better idea.

> 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.)
>
The more I think about it function.__name__ when assigned like this 
might be better served as `'<anon: %s>' % (whatever_you_assigned_to,)`


More information about the Python-ideas mailing list