Date: 3 Apr 2023

Module : mypy


Installation : pip install mypy


About:

Add type annotations to your Python programs, and use mypy to type check
them. Mypy is essentially a Python linter on steroids, and it can catch
many programming errors by analyzing your program, without actually having
to run it. Mypy has a powerful type system with features such as type
inference, gradual typing, generics and union types.


Sample:

$ pip install mypy

$ cat headlines.py

def headline(text: str, align: bool = True) -> str:

    if align:

return f"{text.title()}\n{'-' * len(text)}"

    else:

return f" {text.title()} ".center(50, "o")


print(headline("python type checking"))

print(headline("use mypy", align="center"))

$ mypy headlines.py

headlines.py:10: error: Argument "align" to "headline" has incompatible
type "str"; expected "bool"

$ cat headlines.py

def headline(text: str, centered: bool = False):

    if not centered:

return f"{text.title()}\n{'-' * len(text)}"

    else:

return f" {text.title()} ".center(50, "o")


print(headline("python type checking"))

print(headline("use mypy", centered=True))

$ mypy headlines.py ## No output means no errors


Reference:

https://pypi.org/project/mypy/

https://realpython.com/lessons/type-checking-mypy/
_______________________________________________
Chennaipy mailing list
Chennaipy@python.org
https://mail.python.org/mailman/listinfo/chennaipy

Reply via email to