Using type hints for attributes and properties

When using mypy, we'll need to provide type hints for the attributes of a class. This is generally handled through the __init__() method. Most of the time, the parameter type hints are all that's required.

In previous examples, we defined classes like this:

class RTD_Solver:

def __init__(
self, *,
rate: Optional[float] = None,
time: Optional[float] = None,
distance: Optional[float] = None
) -> None:
if rate:
self.rate = rate
if time:
self.time = time
if distance:
self.distance = distance

The type hints on the parameters are used to discern the types for the instance variables, self.rate, self.time, and self.distance.

When we assign default values in the __init__() method, we have two common design patterns.

  • When we can compute a value eagerly, the type can be discerned by mypy from the assignment statement.
  • When a default None value is provided, the type will have to be stated explicitly.

We may see assignment statements such as the following:

self.computed_value: Optional[float] = None

This assignment statement tells mypy that the variable will either be an instance of float or the None object. This style of initialization makes the class attribute types explicit. 

For property definitions, the type hint is part of the property method definition. We'll often see code like the following:

@property
def some_computed_value(self) -> float: ...

This definition provides a clear statement for the type of object.some_computed_value. This is used by mypy to be sure the types all match among the references to this property name.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset