python / python/typing

`isinstance` check with nested `Protocol`.

Open
#1,257 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: feature
Dominant language
Python
Stars
1.8k
Forks
302
Avg merge
23h
Merged PRs (30d)
8

Description

isinstance(obj, ProtocolSubclass) only checks the the existence of ProtocolSubclass's methods on obj and not the type signature. To provide deeper checks, maybe isinstance could check attributes/methods on ProtocolSubclass that are themselves a Protocol.

A small example showing the change in behavior:

@runtime_checkable
class FooLike(Protocol):
    attr: str

@runtime_checkable
class BarLike(Protocol):
    attr: FooLike

@dataclass
class Foo:
    attr: str = "test"

@dataclass
class Bar:
    attr: Foo

foo = Foo()
bar = Bar(foo)

# No change in current behavior
assert isinstance(foo, FooLike)  # passes
assert isinstance(bar, BarLike)  # passes
assert isinstance(bar, FooLike)  # passes

# Change in behavior
assert not isinstance(foo, BarLike)  # NOT because `BarLike.attr` should be `FooLike` and `foo.attr` is not

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Begin with the runtime behavior of isinstance(obj, ProtocolSubclass) and the @runtime_checkable Protocol examples in the report. Compare the current shallow attribute-existence checks with the requested nested Protocol behavior, then use the assertions in the example to define completion.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.