-
Notifications
You must be signed in to change notification settings - Fork 479
2023 03 07 Session on typing
Richard Stromer edited this page Mar 8, 2023
·
1 revision
https://docs.python.org/3/library/typing.html
First introduced in Python 3.5
- Wrong types are worse than no types
- Not homogenous ecosystem and environments (there are multiple type checkers, python versions, operating systems, etc)
- Precision vs. simplicity (how ‘correct’ do we want to define our types:
str
vs.Literal["multiplicative", "additive"]
) - Default parameters and
None
plus our structure of nested dataclasses - Typing heavily relies on good typing (especially with 3rd party projects)
- numpy (has different types, goes beyond regular python type system)
- pandas (needs stubs, wraps a lot of data, hard to know and define internal structure of dataframes)
- dataclasses (are not very type friendly, make it difficult to deal with default parameters)
- Start early with typing (easy to do it on the fly, so much extra effort to start with it later)
- Be pragmatic about typing
- Do not make it overly complex (
str
is good enough often, specific choices might be nice, but are not essential)
- Do not make it overly complex (
- Create custom types to avoid repetition and secure typing across the project
- Typing helps to prevent or catch errors earlier
- Nice ecosystem around type validation (can save you a lot of manual checks)
- How to best combine docstrings with typings (heavy overlap for parameters)?
- Sphinx docs
- 1-2 standard examples (e.g. where you use Optional or so)
- What specific troubles did you run into when adding typing to excisting code? E.g. using None for a str
- Any hacks how to adapt code most efficiently?
- What problems did you run into with runing pyright on the refactored code? What were often seen pyright error (gab es typische Strukturen in unserem Code, die sich mühsam refactoren liesen? ... du hattest die internen Code Failures angesproche ... vielleicht hast du ja 1-2 examples.
- https://docs.python.org/3/library/typing.html
- https://realpython.com/python-type-checking/#the-mypy-project
- https://docs.pydantic.dev/
a = 10
print(a)
a = "str"
print(a)
# Avoiding circular imports with TYPE_CHECKING
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from sample2 import multiple
from sample import add
from pydantic import validate_arguments, ValidationError
from neuralprophet import NeuralProphet
@validate_arguments
def add(x: DataFrame, y: multiple) -> int:
# if isinstance(x, int):
# raise ValueError("x must be int")
# if isinstance(y, int):
# raise ValueError("x must be int")
# Could be replaced by https://docs.pydantic.dev/
return x + y
add(a, 5)
add("str", [1, 2, 3])
add(1, 2)
NeuralProphet(
yearly_seasonality="auto"
)