You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Since ClassVar's of Type Variable is not allowed is there anything better that can be done then BadSrv?
fromtypingimportClassVar, TypeVar, ProtocolclassMsg(Protocol): ...
RequestT=TypeVar('RequestT', bound=Msg)
ResponseT=TypeVar('ResponseT', bound=Msg)
#IdealclassSrv(Protocol[RequestT, ResponseT]):
Request: ClassVar[type[RequestT]]
Response: ClassVar[type[ResponseT]]
#Jank with TypeAlias, but not supported in protocolclassSrvTypeAlias(Protocol[RequestT, ResponseT]):
type Request=type(RequestT)
type Response=type(ResponseT)
#Current SolutionclassBadSrv(Protocol):
Request: ClassVar[type[Msg]]
Response: ClassVar[type[Msg]]
#Example Service for referenceclassDescribeParameters:
fromrcl_interfaces.srv._describe_parametersimportDescribeParameters_RequestasRequestfromrcl_interfaces.srv._describe_parametersimportDescribeParameters_ResponseasResponse
Simply omit the ClassVar in the protocol definition. Type checkers will then treat these attributes as instance variables. The only downside to this approach is that users of the protocol will be able to overwrite the default value of the attribute (which is a class variable) with an instance value. That's probably something you'd want a type checker to prevent, but there's currently no official way to do this in the typing spec.
This limitation was discussed in the typing forums a while back. In response, I added support in pyright for Final attributes in a protocol definition. The typing spec doesn't officially allow or disallow Final attributes in a protocol. It's something that we could formalize if it's generally useful. Mypy currently rejects this usage.
Protocols are typically used to describe the shape of an object (a class instance), but they can be used to describe the shape of a class object (i.e. an instance of type). That may work for you in this case depending on whether there are other attributes and methods of Srv that you want to include in the protocol definition. This approach avoids the need to describe Request and Response as class variables. From the perspective of the class object, they are simply instance variables.
Here's the relevant part of the typing spec. In particular, it says:
A class object is considered an implementation of a protocol if accessing all members on it results in types assignable to the types of the protocol members.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Since ClassVar's of Type Variable is not allowed is there anything better that can be done then
BadSrv?All reactions