Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Uses for Intersection in type hints #1511

Closed
ViktorSky opened this issue Nov 24, 2023 · 1 comment
Closed

Uses for Intersection in type hints #1511

ViktorSky opened this issue Nov 24, 2023 · 1 comment
Labels
topic: feature Discussions about new features for Python's type annotations

Comments

@ViktorSky
Copy link

The idea in proposing Intersection is to create type hints that support type transformations, since it is not possible to support this behavior without using inheritance.
Furthermore, it becomes much more complicated when trying to use it in overloads.

from typing import TypeVar, Protocol, TYPE_CHECKING, dataclass_transform

ModelT = TypeVar("ModelT", bound=type)

class CreatedModel(Protocol):
    def dump(self) -> str: ...

@dataclass_transform()
def create_model(cls: ModelT) -> ModelT:
    ...  # adding attributes
    return cls

class CustomerModel:
    id: int
    name: str

if TYPE_CHECKING:
    assert issubclass(CustomerModel, CreatedModel)

cls_type = CustomerModel  #  type[<subclass of CustomerModel and CreatedModel>]

In this case, I assume that this tool typing.Intersection exists. It should work similar to typing.Union, but the actual type meets the arguments of this as protocols

from typing import TypeVar, Protocol, dataclass_transform
from typing import Intersection  # not exist

ModelT = TypeVar("ModelT", bound=type)

class CreatedModel(Protocol):
    def dump(self) -> str: ...

@dataclass_transform()
def create_model(cls: ModelT) -> Intersection[ModelT, type[CreatedModel]]:
    ...
    return cls

@create_model
class CustomerModel:
    id: int
    name: str

This implementation would help the more efficient development of dynamic classes by linking with typevar so as not to lose a lot of information during its creation.

@ViktorSky ViktorSky added the topic: feature Discussions about new features for Python's type annotations label Nov 24, 2023
@JelleZijlstra
Copy link
Member

Duplicate of #213.

See also https://github.com/CarliJoy/intersection_examples where there is work towards a PEP on Intersection.

@JelleZijlstra JelleZijlstra closed this as not planned Won't fix, can't repro, duplicate, stale Nov 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic: feature Discussions about new features for Python's type annotations
Projects
None yet
Development

No branches or pull requests

2 participants