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

How to find type parameter with respect to a specific base? #110

Open
wouterdb opened this issue Feb 11, 2025 · 1 comment
Open

How to find type parameter with respect to a specific base? #110

wouterdb opened this issue Feb 11, 2025 · 1 comment

Comments

@wouterdb
Copy link

Problem

I have a generic type that wants to know its own generic parameter at runtime.
I can only get this to work in simple cases.

I also tried to capture it by overriding __class_get_item__ but that didn't work.

I there any way to capture the type parameter?

Example

class Reference[T]:

    @classmethod
    def get_reference_type(cls) -> type[T] | None:
        # this will work only when directly extending Reference[T]
        for g in cls.__orig_bases__:  # type: ignore
            if typing_inspect.is_generic_type(g) and typing.get_origin(g) == Reference:
               return typing.get_args(g)[0]


class Test(Reference[str]):
    pass

print(Test.get_reference_type()) # <class 'str'>

class Test2[T](Reference[T]):
    pass

class Tx(Test2[str]):
    pass

print(Tx.get_reference_type()) # None

Ideal solution

print(typing_inspect.parameter_in_base(Test, Reference))  # <class 'str'>
print(typing_inspect.parameter_in_base(Test2[str], Reference))  # <class 'str'>
print(typing_inspect.parameter_in_base(Tx, Reference))  # <class 'str'>

I don't know if this is even possible.

@wouterdb
Copy link
Author

I found this issues, python/typing#629

Can I conclude from that that this is currently not possible?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant