Skip to content

Make Protocols inheritable. #141774

@jymchng

Description

@jymchng

Feature or enhancement

Proposal:

Currently, typing.runtime_checkable does not work with 'Protocols' that were inherited from typing.Protocol.

Consider:

from typing import Protocol, runtime_checkable

@runtime_checkable
class Reader(Protocol):

    def read(self, source: object):
        ...

@runtime_checkable
class Writer(Protocol):

    def write(self, output: object):
        ...

@runtime_checkable
class ReaderWriter(Reader, Writer):
    ...

Playground

Writing the following does make it work:

from typing import _ProtocolMeta, TypeVar, Generic, runtime_checkable

_T = TypeVar("_T")

@runtime_checkable
class BaseProtocol(Generic[_T], metaclass=_ProtocolMeta):

    _is_protocol = True  

@runtime_checkable
class Reader(BaseProtocol):

    def read(self, source: object):
        ...

@runtime_checkable
class Writer(BaseProtocol):

    def write(self, output: object):
        ...

@runtime_checkable
class ReaderWriter(Reader, Writer):
    ...

Playground

Very often, we might want to inherit from protocols and run runtime checks on them. However, this workaround of setting _is_protocol = True on the base class does not seem reliable.

Any plans to consider having @runtime_checkable to work on subclasses of Protocol?

Thank you.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions