Gradual Typing for Python 3 (AKA PEP 484) Eli Gur (Using GvR slides) [email protected] PyCon IL, May 3rd, 2016 Outline • Overview, motivation • Syntax • Discussion, history • Conclusion? • Q&A Why a type checker • Find bugs sooner • in annotated code • The larger your project the more you need it • annotations help spelunking code • Large teams are already running static analysis • Google, Dropbox building their own • also products like Semmle Why type hints • Help the type checker • in dynamic Python the flow of objects is hard to follow • Serve as (additional) documentation • replace existing docstring conventions • Help IDEs • improve suggestions • improve interactive code checks Why oh why • Python is dynamically typed and we like it that way! • Yes, and… • large projects are already using static analysis tools • but current static checkers are often stumped by dynamic typing • it's still optional! • in fact, in PY3.5 it's provisional (PEP 411) • no code will break Overview • Static type checker a separate program • like a linter; developer chooses whether to use it • Function annotations for type hints • in your code; only used by the type checker • Stub files to annotate code you cannot change • dummy declarations seen only by the type checker Why stub files • C extensions (stdlib or otherwise) • 3rd party packages you can't update • Legacy code you don't want to change • PY2 compatibility • There's no time to annotate the world • new stub files can be released separately Type hints outline • Gradual typing basics • The typing.py module • Annotations • Generics • Pragmatics Gradual typing basics • Type hints for some code def greeting(name: str) -> str: return "Hello, {}.".format(name) • No type hints for other code def greet(name): print(greeting(name)) • Something useful happens where they meet Gradual typing principle • Annotated code must conform to the type hints • Un-annotated (dynamic) code always checks OK • Absence of type hint === type hint of Any • # does not complain about use of Any as a str def greet(name: Any) -> Any: print(greeting(name))
Description: