0

Look the code below:

class A():
    pass

class B():
    def __init__(self) -> None:
        self.a: A = None

b = B()
assert (b.a.something == 'A') or (something(b) == 'A') or (something(b.a) == 'A')

something is a method or function to call to get the answer desired.

I want to recover at runtime the type annotation for property a of the class B.

In other words, I want to get a return saying that B.a would be of type A.

There are any way to get it?

Thanks for help.

Fernando Lima
  • 101
  • 1
  • 7
  • `b.a` is `None`, it's the value you assign in the initializer. The code you've posted will never have `A` as the type of `b.a` or any instance of `B.a`. Now, assuming that you assign an instance of `A` to `b.a`, you may get the type via the builtin function `type()`. Technically, you could also get the class name via `b.a.__class__`, but `type()` is preferable. Lastly, if you're merely testing that `b.a` is of type `A`, use `isinstance()`. To understand these builtins, type `help(type)` and `help(isinstance)` in the interactive prompt. – Michael Ruth Mar 15 '21 at 19:26
  • Does not care what is the type of the value of a. What I want is just the type described in the annotation. The type of the value of property b.a is irrelevant. I need to take the annotation. – Fernando Lima Mar 15 '21 at 19:52
  • If you redefine `B` with class-level type hints, `typing.get_type_hints()` will allow you to access the type annotations. Take a look at https://stackoverflow.com/questions/52838204/how-to-get-class-variables-and-type-hints – Michael Ruth Mar 15 '21 at 20:12
  • Thanks. It is interesting! Unfortunately, it does not work for the class style that is used inside the application. I really need that this feature can works at this example. I found, few minutes ago, the inspect module, that can return the source code to be parsed, but I guess that should have a better way to do it. – Fernando Lima Mar 15 '21 at 21:09

0 Answers0