How can I add type annotation for the attribute that is dynamically assigned to a class?

Viewed 38

Assume I have an existing class like below.

class Animal:

  name: str

  def __init__(self, name: str) -> None:
    self.name = name

  def get_name(self) -> str:
    return self.name

And in another class, I assign another attribute to this class.

class Type:
  """Another class that is dynamically assigned to one of Animal attributes."""

class TestCase:

  animal: Animal

  def __init__(self, name: str) -> None:
    self.animal = Animal(name)
    self.animal.type = Type()

How can I make a type annotation to let TestCase class knowing about animal.type: Type?

1 Answers

You should extend your Animal class to define the type attribute

class TypedAnimal(Animal):

    _type: Type

class TestCase:

  animal: Animal

  def __init__(self, name: str) -> None:
    self.animal = TypedAnimal(name)
    self.animal._type = Type()

Note, type is a builtin, so it is better not to use it in your code as an identifier of an attribute. You could use _type instead.

Related