Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 675
James Schinner Avatar asked Jun 12 '26 15:06

James Schinner


2 Answers

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>
like image 68
Carson Cook Avatar answered Jun 14 '26 03:06

Carson Cook


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'].

like image 24
Davis Herring Avatar answered Jun 14 '26 04:06

Davis Herring



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!