18

Why does the __get__ method in a python descriptor accept the owner class as it's third argument? Can you give an example of it's use?

The first argument (self) is self evident, the second (instances) makes sense in the context of the typically shown descriptor pattern (ex to follow), but I've never really seen the third (owner) used. Can someone explain what the use case is for it?

Just by way of reference and facilitating answers this is the typical use of descriptors I've seen:

class Container(object):
    class ExampleDescriptor(object):
        def __get__(self, instance, owner):
            return instance._name 
        def __set__(self, instance, value):
            instance._name = value
    managed_attr = ExampleDescriptor()

Given that instance.__class__ is available all I can think of is that explicitly passing the class has something to do with directly accessing the descriptor from the class instead of an instances (ex Container.managed_attr). Even so I'm not clear on what one would do in __get__ in this situation.

4 Answers 4

13

owner is used when the attribute is accessed from the class instead of an instance of the class, in which case instance will be None.

In your example attempting something like print(Container.managed_attr) would fail because instance is None so instance._name would raise an AttributeError.

You could improve this behavior by checking to see if instance is None, and it may be useful for logging or raising a more helpful exception to know which class the descriptor belongs to, hence the owner attribute. For example:

        def __get__(self, instance, owner):
            if instance is None:
                # special handling for Customer.managed_attr
            else:
                return instance._name 
4
  • 1
    "logging or raising a more helpful exception" Thanks.
    – Finn
    Jan 3, 2012 at 23:09
  • Why not to also implement managed class level attributes? For example, when an existing class data attribute would benefit from being seen in different units. Say, Room.default_temperature_C, Room.default_temperature_F? Isn't it the more obvious use case, or am I missing something?
    – max
    Sep 17, 2012 at 21:18
  • @max: you are missing something ;) -- ask it as a regular question if you want a detailed answer. May 19, 2014 at 21:54
  • The OP in this post made an insightful suggestion: the same functionality could be achieved with a single argument instance always bound to the originating object, regardless of whether the originating object is a class instance or a class (i.e. a metaclass instance). If that information is really needed, one could just check using isinstance(instance, type). So I’m not sure anymore your answer is valid.
    – Géry Ogam
    Mar 28, 2021 at 17:28
2

When the descriptor is accessed from the class, instance will be None. If you have not accounted for that situation (as your example code does not) then an error will occur at that point.

What should you do in that case? Whatever is sensible. ;) If nothing else makes sense you could follow property's example and return the descriptor itself when accessed from the class.

2
  • Any chance you can explain how returning the descriptor is sensible for property?
    – Finn
    Jan 3, 2012 at 23:10
  • 3
    @Finn: Something is there, so something should be returned. Since there is no instance to get a value from, the descriptor object is the next best choice. If you had a custom descriptor with an actual (default) class value, then you should return that when accessed via the class. Jan 3, 2012 at 23:24
1

Yes, it's used so that the descriptor can see Container when Container.managed_attr is accessed. You could return some object appropriate to the use case, like an unbound method when descriptors are used to implement methods.

1

I think the most famous application of the owner parameter of the __get__ method in Python is the classmethod decorator. Here is a pure Python version:

import types

class ClassMethod:
    "Emulate PyClassMethod_Type() in Objects/funcobject.c."

    def __init__(self, f):
        self.f = f

    def __get__(self, instance, owner=None):
        if instance is None and owner is None:
            raise TypeError("__get__(None, None) is invalid")
        if owner is None:
            owner = type(instance)
        if hasattr(self.f, "__get__"):
            return self.f.__get__(owner)
        return types.MethodType(self.f, owner)

classmethod binds the first parameter of a function to a subclass of the class owning the classmethod instance that is found during an attribute lookup originating from an object. The resulting callable of this binding is a method. To derive that subclass from the originating object, classmethod need know whether the originating object is an instance (in which case it uses the type of the instance provided by the instance parameter) or a subclass of the owning class (in which case it directly uses the subclass provided by the owner parameter). That information is provided by the instance parameter which is None in the former and not None in the latter. So classmethod works for attribute lookup originating from instances but also from subclasses thanks to the owner parameter:

class A:

    @ClassMethod
    def name(cls):
        return cls.__name__


A().name()  # returns 'A' so attribute lookup from an instance works
A.name()    # returns 'A' so attribute lookup from a class works too

More information in this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.