Skip to content

typecheck: support Protocol, TypedDict, Generic, ForwardRef (D4 set 3) #98

@Technologicat

Description

@Technologicat

Context

The runtime type checker (unpythonic.typecheck.isoftype) has been expanded in 2.0.0 to support many more typing features. The remaining unsupported features are the hard cases:

Remaining types

  • Protocol — full structural subtyping. Would need to inspect which methods/attributes the protocol requires and check that the value's class provides them. Heavy to implement correctly, and typing.runtime_checkable already provides a partial solution for protocols that opt in.

  • TypedDict — need to check required vs. optional keys, and verify value types per-key. Medium difficulty. The metadata is available via __required_keys__, __optional_keys__, and __annotations__.

  • Generic — abstract; unclear what "value matches Generic[T]" means at runtime. Possibly not meaningful for isoftype at all.

  • ForwardRef — a string reference to a type that must be resolved in some namespace. Would need the caller to supply a namespace (or use the caller's frame globals), adding API complexity.

Discussion

These are listed roughly in order of potential usefulness for unpythonic.dispatch. Protocol and TypedDict have concrete use cases; Generic and ForwardRef are more questionable.

For Protocol, it may be worth checking whether typing.runtime_checkable + isinstance is sufficient, rather than reimplementing structural subtyping.

Other typing features that were missing pre-2.0.0 were completed in commits 665cc4b through 6aa72ea.

Metadata

Metadata

Assignees

No one assigned

    Labels

    discussionThinking it over - comments welcome!enhancementNew feature or request

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions