James Schinner James Schinner - 27 days ago 8
Python Question

Python: test descriptors assigned correctly

Considering this example:

>>> class Bar(object):
...
... def __init__(self, name):
... self.name = name
... def __set__(self, instance, value):
... setattr(instance, self.name, value)
... def __get__(self, instance, owner):
... return getattr(instance, self.name, owner)
...
>>> class Foo(object):
... bat = Bar('bat')
...
>>> Foo.bat
<class 'Foo'>
>>> type(Foo.bat)
<class 'type'> # how would you get <class 'Bar'> ?


I want to write some
pytests
that assert the correct descriptor has been assigned to the correct attribute.

But I don't seem to be able to check the type of a descriptor once it has been assigned

Answer Source

I'm not sure what you're trying to do with your descriptor, but typically you want to pass back the descriptor itself when an instance is not passed:

class Bar(object):
    def __init__(self, name):
        self.name = name
    def __set__(self, obj, value):
        setattr(obj, self.name, value)
    def __get__(self, obj, cls):
        if obj is None:
            return self
        return getattr(obj, self.name)

class Foo(object):
    bat = Bar('bat')

Foo.bat
# <__main__.Bar at 0x7f202accbf50>