How do I correctly add type-hints to Mixin classes?

后端 未结 5 1823
梦谈多话
梦谈多话 2021-02-13 02:33

Consider the following example. The example is contrived but illustrates the point in a runnable example:

class MultiplicatorMixin:

    def multiply(self, m: in         


        
5条回答
  •  终归单人心
    2021-02-13 02:59

    Try with:

    from typing import Type, TYPE_CHECKING, TypeVar
    
    T = TypeVar('T')
    
    
    def with_typehint(baseclass: Type[T]) -> Type[T]:
        """
        Useful function to make mixins with baseclass typehint
    
        ```
        class ReadonlyMixin(with_typehint(BaseAdmin))):
            ...
        ```
        """
        if TYPE_CHECKING:
            return baseclass
        return object
    
    

    Example tested in Pyright:

    class ReadOnlyInlineMixin(with_typehint(BaseModelAdmin)):
        def get_readonly_fields(self,
                                request: WSGIRequest,
                                obj: Optional[Model] = None) -> List[str]:
    
            if self.readonly_fields is None:
                readonly_fields = []
            else:
                readonly_fields = self.readonly_fields # self get is typed by baseclass
    
            return self._get_readonly_fields(request, obj) + list(readonly_fields)
    
        def has_change_permission(self,
                                  request: WSGIRequest,
                                  obj: Optional[Model] = None) -> bool:
            return (
                request.method in ['GET', 'HEAD']
                and super().has_change_permission(request, obj) # super is typed by baseclass
            )
    
    >>> ReadOnlyAdminMixin.__mro__
    (, )
    

提交回复
热议问题