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
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>
You can override the usual lookup (which uses the very descriptor you're trying to see, whether or not you call type on the result) with vars(Foo)['bat'].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With