[Python-ideas] Allowing def to assign to anything

Alexander Walters tritium-list at sdamon.com
Mon Oct 26 03:09:13 EDT 2015


to be clear, I propose the following to be equivalent (to clear up what 
I mean)

```
# classes:

class Foo:
     def bar(self):
         pass

# vs

class Foo:
     pass

def Foo.bar(self):
     pass

# Instances:

def foo(args): pass

inst = Class()
inst.foo = foo

# vs

inst =  Class()

def inst.foo(args): pass

```

does this make that clear?

On 10/26/2015 03:05, Andrew Barnert 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.
>
> As for the binding to self, that doesn't happen at assignment time, so it can't happen the same way as at assignment time. The binding happens later, each time the method is looked up. If an object doesn't have an attribute of the looked up name, but its type does, the type's attribute's __get__ method is called with the instance. So, there's nothing to do here at all; functions already have a __get__ method that returns a bound method (and if you assign a function to an instance rather than a type, it doesn't get bound). This is all explained pretty clearly in the descriptor HOWTO.
>
> But descriptors also work for setting, not just getting (which is how @property works), and that's what I was asking about. If I write "spam.eggs = 0", and type(spam) has a member named "eggs", its __set__ method will get called with the instance (spam) and the value (0). So, if I write "def spam.eggs(): pass", does it call the same descriptor method?
>
>>   I do not propose that assigning to classes in this way be considered a good idea.
> OK, but unless you're actually proposing to not allow it, you still need to work out what it would do.
>
>> as for when assigned to a data structure, my admittedly naive idea would be to set the name to '__none__' or some such.  I am open to other ideas though.
> Functions defined with lambda get the name "<lambda>", so you'd probably want angle brackets here as well. But otherwise that seems reasonable, I guess.
>
>>> On 10/26/2015 02:19, Andrew Barnert wrote:
>>> Seems interesting.
>>>
>>> What's the name of the defined function? For an attribution like "spam.eggs" you'd probably want it to be "eggs", and I guess for "spam['eggs']" as well, but what about "spam['two words']" or "spam[2]"?
>>>
>>> I assume the qualname is just the name.
>>>
>>> Also, would this go through the descriptor mechanism if you def an attribution?



More information about the Python-ideas mailing list