[Chennaipy] Chennaipy - Monday Module - 03 Apr 2023

selvi dct selvi.dct at gmail.com
Mon Apr 3 01:50:12 EDT 2023


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/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.python.org/pipermail/chennaipy/attachments/20230403/7061e8ba/attachment.html>


More information about the Chennaipy mailing list