Can Python __set__ handle ever be called with instance = No?

Imagine I have a Python descriptor :

class MyDesc(object): def __get__(self, instance, instance_type=None): return 'Blue berries' def __set__(self, instance, value): print 'called with', instance, value class MyClass(object): desc = MyDesc() 

Is there a way in the normal run of things that tar __set__ will be called with None for the instance argument? I mean, not doing something like

 MyClass.__dict__['desc'].__set__(None, 'ants bees cats') 

It doesn't look like this:

 MyClass.desc = 'blah' setattr(MyClass, 'desc', 'blah') 

The reason I ask is to see the security coding in Django to avoid this scenario, and I wonder if this is necessary.

+4
source share
2 answers

I think you are right to question this test, and I cannot find an instance method to be None in this code. The documentation also shows that instance never be None :

 object.__set__(self, instance, value) 

Called to set the attribute in the instance instance of the owner class to the new value value .

I assume that instance was tested on None in __get__ for a good reason, and that the same test ended up in __set__ with pure mimetism.

+3
source

Regarding security coding, I see some code checking for an instance on __get__ (which is called for MyClass.desc ), but not on __set__ . The reason this does not happen with __set__ is because setting the link in the class replaces the entire link to the descriptor.

I would recommend over-defensive programming simply because other code might find some way to go wrong with or without your help. This is enough to prevent unexpected results, and not to protect against active violence.

0
source

Source: https://habr.com/ru/post/1479478/


All Articles