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

constrain a generic type with an alias derived from a union type in Python #18316

Closed
GENDRAUD opened this issue Dec 20, 2024 · 1 comment
Closed
Labels

Comments

@GENDRAUD
Copy link

I know to constraint a generic being a type in a list. See the example

from typing import TypeVar

T = TypeVar("T", int, str)

def combine2(a: T, b: T) -> T:
    return  a + b

r: int = combine2(2, 2)
print(r)

s: str = combine2("Hello, ", "World!")
print(s)

If I want to do the same with the python 3.13 generic syntax, I write this code:

def combine2[T: (int , str)](a: T, b: T) -> T:
    return a + b

r: int = combine2(2, 2)
print(r)

s: str = combine2("Hello, ", "World!")
print(s)

It works but if I have several function taking a generic constraint with the same 2 type. I have to write every time the same T: (int , str)
It is not good. For instance If to change the constraint, I have to change it everywhere.

Therefore what I propose is a way to say that type that T can take comes from a Union type. If the constraint change. It has thefollowing advantage. If I have to change the constraint I only have to change the union type.

concrete example of what I would like to have

type constraint= int | str

def combine2[T from constraint](a: T, b: T) -> T:
    return a + b

r: int = combine2(2, 2)
print(r)

s: str = combine2("Hello, ", "World!")
print(s)

I don t think this feature exist. I already ask. There (https://stackoverflow.com/questions/79126319/how-to-constrain-a-generic-type-with-an-alias-derived-from-a-union-type-in-pytho) for instance

@sterliakov
Copy link
Contributor

This isn't something mypy can introduce as a type checker - you're proposing either a python syntax change or at least a new typing core feature. Consider asking on Python's Discourse (https://discuss.python.org/c/typing/32) instead.

@JelleZijlstra JelleZijlstra closed this as not planned Won't fix, can't repro, duplicate, stale Dec 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants