yeiniel
yeiniel

Reputation: 2456

How to annotate function result based on argument attribute

Lets suppose i have the following types

import typing

class A:
  pass

class B:
  @property
  def a_factory(self): -> typing.Type[A]
    return A

my problem is howto define a type for a callable that takes B instance as argument and return an instance of the a_factory attribute.

What i have so far:

C = typing.Callable[[B], ?]

I don't want to use A directly because i want the C type to convey the requirement of using B.a_factory factory to produce the return value. Any ideas?

Upvotes: 0

Views: 65

Answers (1)

ajz34
ajz34

Reputation: 163

import typing

class A:
    pass

class B:
    @property
    def a_factory(self) -> typing.Type[A]:
        return A

b = B()  # an instance of class B

C = typing.get_type_hints(B.a_factory.fget)["return"]
C = typing.get_type_hints(b.__class__.a_factory.fget)["return"]
print(C)  # typing.Type[__main__.A]
  • Maybe a property is not simply a callable; since the code above only defines getter of property, so we need fget to retrive the getter function, then use get_type_hints to get returned type.
  • To retrive the class B from instance b, we need __class__ attribute.

Upvotes: 1

Related Questions