« Back to Index

[Python Type Hinting MyPy]

View original Gist on GitHub

Tags: #mypy #python #types #hinting

Generating stubs.md

You need to generate stubs that are missing, since dependencies such as boto3 doesn’t provide type hints (as do most packages unfortunately). Mostly we don’t really care about external packages, and type hinting is mostly useful as a documentation tool and can help with autocompletion tools.

So typically you’ll run MyPy with: --ignore-missing-imports.

Note: alternatively specify which modules you want to ignore like this.

Consider the following code:

import boto3

from botocore.client import BaseClient

client = boto3.client('cognito-idp')

def foo(client: BaseClient):
    print('hey')

foo('ccccc')

MyPy will not see any problems here because we’ll either have generated a stub for boto3 or we would be skipping the import altogether.

To generate the missing stub for boto3:

  1. generate stubs: stubgen --recursive botocore
  2. MYPYPATH='./out' mypy your_file.py

./out is the default directory stubgen where stubgen puts the stubs

Then executing MyPy will pick up the error:

test.py:12: error: Argument 1 to "foo" has incompatible type "str"; expected "BaseClient"

Python Type Hinting MyPy.py

from typing import Union

Number = Union[int, float]

def add(x: Number = 10, y: Number = 5) -> Number:
  print(x, y)