DEV Community

Cover image for IntelliType: Python Type Hinting with Hoverable Docstrings
crimson206
crimson206

Posted on

IntelliType: Python Type Hinting with Hoverable Docstrings

IntelliType

I recently published a Python type-hint library called intelli-type. The main purpose is to enhance type-hinting with Intellisense.

Intellisense

When using IntelliType, you need to define custom type hints.

class AudioFeature(IntelliType[Tensor], Generic[T]):
    """
    VggishOutput representation.

    Shape: (batch_size, 1, channels)
    - channels: Number of audio features

    Input Audio Waves -> AudioFeature
    """
Enter fullscreen mode Exit fullscreen mode

The type AudioFeature is equivalent to Tensor.

Even though you define the type when you create AudioFeature,
you still need to specify the type when you use it for type hinting.

def forward(
    self, feature_map: FeatureMap[Tensor], audio_feature: AudioFeature[Tensor]
) -> FusionMap[Tensor]:
    pass
Enter fullscreen mode Exit fullscreen mode

Adding Generic[T] enhances Intellisense.

# Intellisense with Generic[T]

(method) def forward(
    self: Self@CrossModalMixer,
    feature_map: FeatureMap[Tensor],
    audio_feature: AudioFeature[Tensor]
) -> FusionMap[Tensor]
Enter fullscreen mode Exit fullscreen mode
# Intellisense without Generic[T]

(method) def forward(
    self: Self@CrossModalMixer,
    feature_map: FeatureMap,
    audio_feature: AudioFeature
) -> FusionMap
Enter fullscreen mode Exit fullscreen mode

deep-learning-example

Gif. Runtime Example

Strict Annotation

If you have already defined AudioFeature as Tensor, you can't use this type with other types. The syntax below will cause an error.

def func(
    audio_feature: AudioFeature[str]
):
    ...
Enter fullscreen mode Exit fullscreen mode

Single Responsibility & Reusability

Traditionally, we write the description of arguments in the docstring of a function.
The same argument can be used in different functions, so we need to repeat the same task. The critical problem is that the descriptions for the same argument are not programmatically connected. If we want to update the description of the argument, we must do it manually.

func_dedicated_docstring
Fig. Function Dedicated Docstring

Using IntelliType, the description for feature_map is written in FeatureMap and can be reused everywhere. You update the docstring in FeatureMap, and the change is applied everywhere programmatically. Therefore, we can write dedicated docstrings for functions and arguments separately.

Namespace

I am pioneering and establishing Micro-wise development. To avoid 'namespace pollution', I am publishing all the modules with the namespace 'crimson'. Therefore,

# import syntax is

from crimson.intelli_type import IntelliType
Enter fullscreen mode Exit fullscreen mode
# install the package with the command line

pip install crimson-intelli-type
Enter fullscreen mode Exit fullscreen mode

Post History

Written: 16/07/2024

Top comments (0)