ARTICLE AD BOX
I have created this abstract base class:
import json from dataclasses import dataclass, InitVar, field from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes, PublicKeyTypes from ..signer.signer import Signer _PubKeyT = TypeVar("_PubKeyT", bound=PublicKeyTypes) _PrivKeyT = TypeVar("_PrivKeyT", bound=PrivateKeyTypes) @dataclass(kw_only=True, repr=False) class Message(Generic[_PubKeyT, _PrivKeyT], ABC): signer: InitVar[Signer[_PubKeyT, _PrivKeyT]] signature: bytes | None = field(default=None, repr=False) @classmethod def deserialize(cls, data: bytes, signer: Signer[_PubKeyT, _PrivKeyT]) -> Self: obj = json.loads(data) payload = base64.b64decode(obj["payload"]) signature = base64.b64decode(obj["signature"]) return cls._from_payload(payload, signature, signer)an implementation of this class is the following
import json from dataclasses import dataclass from typing import Generic, Self, TypeVar import base64 from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes, PublicKeyTypes _PubKeyT = TypeVar("_PubKeyT", bound=PublicKeyTypes) _PrivKeyT = TypeVar("_PrivKeyT", bound=PrivateKeyTypes) @dataclass(repr=False) class Content(Message[_PubKeyT, _PrivKeyT], Generic[_PubKeyT, _PrivKeyT]): content: bytes @property def payload(self) -> bytes: obj = { "content": base64.b64encode(self.content).decode() } return json.dumps(obj, separators=(",", ":"), sort_keys=True).encode() @classmethod def _from_payload(cls, payload: bytes, signature: bytes, signer: Signer[_PubKeyT, _PrivKeyT]) -> Self: obj = json.loads(payload) return cls( content=base64.b64decode(obj["content"]), signature=signature, signer=signer, )which I use like
signed_message = Content.deserialize(signed_message_bytes, self.signer)This results on this pylance warning:
Type of "deserialize" is partially unknown Type of "deserialize" is "(data: bytes, signer: Signer[Unknown, Unknown]) -> Content[Unknown, Unknown]"PylancereportUnknownMemberType (method) def deserialize( data: bytes, signer: Signer[Unknown, Unknown] ) -> Content[Unknown, Unknown]However, explicitly setting the types fixes the warning (all tests pass, etc.)
signed_message = Content[_SigPubT, _SigPrivT].deserialize(signed_message_bytes, self.signer)So pylance cannot infer the signer types. Is this something wrong in my code, or a limitation of pylance? Any idea on how can I get pylance, if possible at all, to infer the types?
