0

Supose that I have:

T = TypeVar('T', bound='Client') 

Now, I want a function that gets the type T and returns Client, or, yet better a class Client.

How I can get it in Python 3.9?

1 Answer 1

1

You can do so via typing_inspect.get_bound from the typing_inspect package. It offers cross-version support for runtime inspection of type annotations:

>>> class Foo: pass >>> T = TypeVar("T", bound=Foo) >>> typing_inspect.get_bound(T) __main__.Foo >>> T = TypeVar("T", bound="Foo") >>> typing_inspect.get_bound(T) ForwardRef('Foo') 

When bound is set to a string, the returned value is a "forward reference". I don't think there's currently a public API to evaluate that to a concrete class. There is a private API that you could use like this:

>>> ref = typing_inspect.get_bound(T) >>> ref._evaluate(globals(), globals(), set()) __main__.Foo 
Sign up to request clarification or add additional context in comments.

6 Comments

Supose that I have x: T Then, I can do x.__bound__.__forward_arg__ to get 'Client'. But I still do not found a way to get it as a class.
Using x.__bound__._evaluate like you pointed worked but needs to pass the module in string like 'model.Client' instead of just 'Client'
Thank you for your help. The use of evaluate can solve my problem.
@FernandoLima The point of using typing_inspect in favor of __bound__ is that it provides a stable public API that works across Python versions. There is no guarantee that __bound__ works in past versions and will work in future versions, as it's not part of the standard. For the other question, it seems that you've already made it work, so it'd be great if you could accept the answer.
Done. I am sorry, I forgot to confirm that I accepted the answer. I should have already done this.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.