Mypy and components


#1

Hello,
How do you deal with mypy and components :

(I use TypeVar to deal with circular import)

UserC = TypeVar("UserC")

class UserComponent(Component):
    def resolve(self, user: JWTUser) -> UserC:
        return get_or_404(User, user.id) #return a User class

def view(user: UserC):
   id = user.id

doing this, mypy will complain that UserC has no attribute id

How can we make mypy understand that UserC hint is in fact a User ?


#2

Why do you need the typevar?

class UserComponent(Component):
    def resolve(self, user: JWTUser) -> User:
        return get_or_404(User, user.id) #return a User class

def view(user: User):
   id = user.id

ought to work fine. Alternatively, you could bind the type var:

UserC = TypeVar("UserC", User)

or, better yet, use a newtype since a type var isn’t really appropriate here as the component isn’t generic:

UserC = NewType("UserC", User)

but then you’ll have to change resolve to

    def resolve(self, user: JWTUser) -> UserC:
        return UserC(get_or_404(User, user.id))

#3

Thank you for your answer but it’s not exactly my trouble.

Maybe my example was bad, so here is another one:

    class Permission:
      blabla

    class PermissionComponent:
       def resolve(self) -> Permission
            return someobject # with type MyObject

    def myview(self, new_object: Permission):
        blabla

how could mypy know that new_object’s type is Myobject and not Permission.

I hope it’s clearer now.
Thanks
jimmy