Python Zero to Heros

Online Absolute Beginner Python Tutorials 

Every Sunday 2pm (UK time/ BST)

Get this slide deck:

slides.com/cheukting_ho/python-type-hint

Recap

Beginner topics:

Python objects, Control flows,

Functions, modeuls, classes and decorators

strings operations and regex with re

Testing:

pytest with fixtures and mock

property-based testing

python linters & auto-formatters

TDD

Intermedite topics:

Iterators, generators, async

Packaging:

generating docs, pypi

What is type hinting?

Type hinting is a formal solution to statically indicate the type of a value within your Python code. It was specified in PEP 484 and introduced in Python 3.5.

- realpython.com

def greeting(name: str) -> str:
    return 'Hello ' + name

Why type hinting?

 

Due to the dynamic nature of Python, inferring or checking the type of an object being used is especially hard.

 

This fact makes it hard for developers to understand what exactly is going on in code they haven't written and, most importantly, for type checking tools found in many IDEs that are limited due to the fact that they don't have any indicator of what type the objects are.

 

https://stackoverflow.com/a/32558710​

Why Type Hints?

  • Helps Type Checkers
  • Helps with documentation
  • Helps IDEs develop more accurate and robust tools

 

Why use Static Type Checkers?

  • Find bugs sooner
  • The larger your project the more you need it
  • Large teams are already running static analysis

 

** Note that it's optional to use type hints

Type Checkers

 

Mypy - the most well known Python type checker

 

pytype - another popular one by Google

Type Hints with IDEs

 

PyCharm - type is added as an annotation for Python 3

 

Atom - packages plug-in: linter-mypy or magicpython

 

VS Code - extention plug-in: pyright

Type hint with docs

 

Using sphinx-autodoc-typehints Sphinx extention to use Python 3 annotations for documenting acceptable argument types and return value types of functions.

 

https://github.com/agronholm/sphinx-autodoc-typehints

Next week:
TBC

Sunday 2pm (UK time/ BST)

There are also Mid Meet Py every Wednesday 1pm

Python Type Hinting

By Cheuk Ting Ho

Python Type Hinting

  • 267
Loading comments...

More from Cheuk Ting Ho