# Type hints and checking in Python: what, why, how James Doss-Gollin 2020-07-09 Keller Group Research Meeting Slides: https://hackmd.io/@jdossgollin/r1qFjK4kD --- ## Types * Python (like **R**, Ruby, JavaScript) is an _interpreted_ language * In a statically typed language, every variable name is bound both to a type (at compile time, by means of a data declaration) to an object. * In a dynamically typed language, every variable name is bound only to an object. --- ## Type hints and mypy In python 3.6+ we can annotate our code with static type hints! ```python class BankAccount: def __init__(self, initial_balance: int = 0) -> None: self.balance = initial_balance def deposit(self, amount: int) -> None: self.balance += amount def withdraw(self, amount: int) -> None: self.balance -= amount def overdrawn(self) -> bool: return self.balance < 0 my_account = BankAccount(15) my_account.withdraw(5) print(my_account.balance) ``` --- ## Why? * improve autocomplete suggestions * better thinking -- what arguments do we want our function to take? * catch bugs sooner with `mypy` --- ## `mypy` checks for inconsistency * Command line: `mypy src --ignore-missing-imports` * In your text editor (eg, [VS Code](https://code.visualstudio.com/docs/python/linting)) **in real time** * On [Travis-CI](https://hackmd.io/@jdossgollin/r1qFjK4kD) (or similar) for a software project ![](https://i.imgur.com/QuzF8Yi.png) --- ## Best practices for installing (_opinionated_) * use conda for **everything** in python * create a more lightweight `environment.yml` with only the packages needed to _run_ the code * create a heavier `environment-dev.yml` with `mypy` (and `pylint`, `black`, etc) * work in `environment-dev` --- ## Learn More * [mypy docs](http://mypy-lang.org/examples.html) * docs of built-in [typing](https://docs.python.org/3/library/typing.html) module -- allows types like `Tuple`, `Iterable`, `Dict[str, Union[float, np.ndarray]]` etc. * [Type Hints - Guido van Rossum](https://www.youtube.com/watch?v=2wDvzy6Hgxg) gives a high-level overview of why this might be useful * [Static Typing in Python - Dustin Ingram](https://www.youtube.com/watch?v=p-nhGq-Wwv8) - like this talk but better and more complete * [Livecoding Madness: Let's Build a Deep Learning Library - Joel Grus](https://www.youtube.com/watch?v=o64FV-ez6Gw) - worth watching for many reasons but excellent demo of how to use type hints in practice
{"metaMigratedAt":"2023-06-15T10:30:17.632Z","metaMigratedFrom":"YAML","title":"What is mypy?","breaks":true,"description":"View the slide with \"Slide Mode\".","slideOptions":"{\"transition\":\"slide\",\"theme\":\"simple\",\"allottedMinutes\":3,\"width\":1600,\"height\":1200}","contributors":"[{\"id\":\"fbc33c75-0378-480d-bdb4-6a27db38ff95\",\"add\":6286,\"del\":3585}]"}
    194 views