Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active January 14, 2020 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Integralist/916c150d64ccafb4bf7ad74650b4a6a9 to your computer and use it in GitHub Desktop.
Save Integralist/916c150d64ccafb4bf7ad74650b4a6a9 to your computer and use it in GitHub Desktop.
[Python Type Hinting MyPy] #mypy #python #types #hinting

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"
from typing import Union
Number = Union[int, float]
def add(x: Number = 10, y: Number = 5) -> Number:
print(x, y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment