[FIXED] Python - TypeHint for Descriptor

Issue

I would like to have a base class for all my descriptors which is of type descriptor:

  1. Is it correct to use the GetSetDescriptorType?
class MyDescriptorBase(GetSetDescriptorType):
  pass

Now when I declare

class MyDescriptor(DescriptorBase):

    def __get__(self, __obj: MyObj, objtype: Type[MyObj] ):
       pass

A pycharm inspection complains:

get() does not match signature.

I have looked up the signature which is:

# types.pyi

def __get__(self, __obj: Any, __type: type = ...) -> Any: ...
  1. Is it an error in inspection or is my declaration wrong?

Solution

No, using GetSetDescriptor class as base is invalid for type checking since this class is final.

You don't really need this base, because descriptors have good support now.

The problem in your definition is missing default value of objtype: parent can be called with one argument and your child - no, so this violates LSP. So the following is compatible:

class MyDescriptor(MyDescriptorBase):
    def __get__(self, obj: MyObj, objtype: type[MyObj] | None = None):
        pass


Answered By - SUTerliakov
Answer Checked By - Marilyn (Python.Easybugfix Volunteer)

Related Posts

Post a Comment