Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

The Benefits of Type Hints

1,514 views

Published on

for PyconTw 2017 3rd Day(June 11th)

Published in: Engineering
  • Be the first to comment

The Benefits of Type Hints

  1. 1. The Bene ts of Type Hints PyCon Taiwan 2017 June 11th 1
  2. 2. Masato Nakamura(中村真人) from Nulab Japan PyCon Taiwan 2017 June 11th
  3. 3. What is Nulab PyCon Taiwan 2017 June 11th
  4. 4. We provide Collaboration software. PyCon Taiwan 2017 June 11th
  5. 5. My Goal You can use Type Hints from today! PyCon Taiwan 2017 June 11th
  6. 6. Not covering today Technical Details PyCon Taiwan 2017 June 11th
  7. 7. Today I will introduce, and talk about the Usage and Bene ts of Type Hints PyCon Taiwan 2017 June 11th
  8. 8. Introduction PyCon Taiwan 2017 June 11th
  9. 9. Introduction What are Type Hints Hisory typing module PyCon Taiwan 2017 June 11th
  10. 10. What are Type Hints Traditional Python code def twice(num): return num * 2.0 using Type Hints def twice(num: double) -> double: return num * 2.0 PyCon Taiwan 2017 June 11th
  11. 11. Type Hints using Type Hints def twice(num: double) -> double: return num * 2.0 C-language Code double twice(double str) { return str * 2.0; } PyCon Taiwan 2017 June 11th
  12. 12. History PyCon Taiwan 2017 June 11th
  13. 13. History Type Hints has a three-part history. PyCon Taiwan 2017 June 11th
  14. 14. Python2 Python 2.x series did not have a way to qualify function arguments and return values, so many tools and libraries appeared to ll that gap. def greeting(name): return 'Hello ' + name greet = greeting("Masato") What is name ? What does greeting return? PyCon Taiwan 2017 June 11th
  15. 15. History PEP implement 3107 Python 3.0 484 Python 3.5 526 Ptyhon 3.6 PyCon Taiwan 2017 June 11th
  16. 16. PEP 3107 adding Function annotations, both for parameters and return values, are completely optional.You can write free text . def compile(source: "something compilable", filename: "where the compilable thing comes from", mode: "is this a single statement or a suite?"): the semantics were deliberately left unde ned. PyCon Taiwan 2017 June 11th
  17. 17. PEP 484 def greeting(name: str) -> str: return 'Hello ' + name PEP-484 Type Hints There has now been enough 3rd party usage for static type analysis, that the community would bene t from a standardized vocabulary and baseline tools within the standard library. “ “ PyCon Taiwan 2017 June 11th
  18. 18. Point in PEP484 It’s not about code generation It’s not going to affect how your compiler complies your code. Your code can still break during run time after type checking. It’s not going to make Python static-typed Python will remain a dynamically typed language, and the authors had no desire to ever make type hints mandatory, even by convention. “ “ PyCon Taiwan 2017 June 11th
  19. 19. return to the PEP484 def greeting(name: str) -> str: return 'Hello ' + name greet = greeting("Masato") # type: str # make greeting message! Hmm , now I'd like to describe variables more easily PyCon Taiwan 2017 June 11th
  20. 20. PEP 526 # PEP 484 def greeting(name: str) -> str: return 'Hello ' + name greet = greeting("Masato") # type: str # make greeting message! # pep 526 def greeting(name: str) -> str: return 'Hello ' + name greet:str = greeting("Masato") # make greeting message! PyCon Taiwan 2017 June 11th
  21. 21. typing module PyCon Taiwan 2017 June 11th
  22. 22. What is the typing module Module introduced when PEP 484 was implemented in 3.5 Provides python with frequently used types such as List, Dict Make the data structure easier with namedtuple from typing import List a: List[int] = [1,2,3] path: Optional[str] = None # Path to module sourde PyCon Taiwan 2017 June 11th
  23. 23. NamedTuple In Python 3.5(PEP 484) Point = namedtuple('Point', ['x', 'y']) p = Point(x=1, y=2) In Python 3.6(PEP 526) from typing import NamedTuple class Point(NamedTuple): x: int y: int p = Point(x=1, y=2) PyCon Taiwan 2017 June 11th
  24. 24. Usage PyCon Taiwan 2017 June 11th
  25. 25. Usage How to write How to get Type Hints Info PyCon Taiwan 2017 June 11th
  26. 26. How to write I talk about PEP526 style def greeting(name: str) -> str: return 'Hello ' + name greet: str = greeting("Masato") PyCon Taiwan 2017 June 11th
  27. 27. difference of PEP484 and PEP526 # pep 484 child # type: bool # cannot allow if age < 18: child = True # type: bool # It's OK else: child = False # type: bool # It's OK # pep 526 child: bool # OK if age < 18: child = True # No need to Write bool else: child = False PyCon Taiwan 2017 June 11th
  28. 28. backward compatibility # We can write pep484 style code in 3.6 backward compatiblity hour = 24 # type: int # PEP 526 style hour: int; hour = 24 hour: int = 24 PyCon Taiwan 2017 June 11th
  29. 29. Attention points PEP3107 style is also OK >>> alice: 'well done' = 'A+' >>> bob: 'what a shame' = 'F-' >>> __annotations__ {'alice': 'well done', 'bob': 'what a shame'} But let's use for Type Hints as much as possible for the future. PyCon Taiwan 2017 June 11th
  30. 30. How to get Type Hints Info Q. where is variable annotation A. at __annotaitons__ >>> answer:int = 42 >>> __annotations__ {'answer': <class 'int'>} PyCon Taiwan 2017 June 11th
  31. 31. Attention We can only nd Class variables . >>> class Car: ... stats: ClassVar[Dict[str, int]] = {} ... def __init__(self) -> None: ... self.seats = 4 >>> c: Car = Car() >>> c.__annotations__ {'stats': typing.ClassVar[typing.Dict[str, int]]} # only ClassVar! We cannot get instance's variables! PyCon Taiwan 2017 June 11th
  32. 32. Bene ts PyCon Taiwan 2017 June 11th
  33. 33. Bene ts Code Style code completion statistic type analysis Our story PyCon Taiwan 2017 June 11th
  34. 34. Code Style Simple is best Explicit is better than Implicit. def greeting(name: str) -> str: return 'Hello ' + name We can check this by Type Hints def greeting(name: str) -> str: return 42 PyCon Taiwan 2017 June 11th
  35. 35. Code Completion We can use code completion in Editor Visual Studio code PyCharm(IntelliJ) PyCon Taiwan 2017 June 11th
  36. 36. example PyCon Taiwan 2017 June 11th
  37. 37. statistic type analysis PyCon Taiwan 2017 June 11th
  38. 38. statistic type analysis for check variable type(no runable code) python has some tools mypy pytypes (not talk) PyCon Taiwan 2017 June 11th
  39. 39. example PyCon Taiwan 2017 June 11th
  40. 40. mypy https://github.com/python/mypy made by JukkaL & Guido can output report We can use!(PEP526 style) PyCon Taiwan 2017 June 11th
  41. 41. mypy $ pip install mypy # if you use Python 2.7 & 3.2-3.4 $ pip install typing PyCon Taiwan 2017 June 11th
  42. 42. mypy example code(example.py) from typing import NamedTuple class Employee(NamedTuple): name: str id: int emp: Employee = Employee(name='Guido', id='x') run $ mypy --python-version 3.6 example.py example.py:16: error: Argument 2 to "Employee" has incompatible type "str"; expected "int" PyCon Taiwan 2017 June 11th
  43. 43. mypy can use in Python2 class MyClass(object): # For instance methods, omit `self`. def my_method(self, num, str1): # type: (int, str) -> str return num * str1 def __init__(self): # type: () -> None pass x = MyClass() # type: MyClass PyCon Taiwan 2017 June 11th
  44. 44. Continuous Integration Jenkins Github + Travis CI Github + CircleCi PyCon Taiwan 2017 June 11th
  45. 45. Continuous Integration we can run mypy on CI systems we can get results If you develop in a team, there are many bene ts ex: If someone issues a pull request for your project, you can review their code PyCon Taiwan 2017 June 11th
  46. 46. example(error) PyCon Taiwan 2017 June 11th
  47. 47. example(success) PyCon Taiwan 2017 June 11th
  48. 48. Bene ts for me We use Fabric for deployment But it is for Only Python2 Python2 will nished at 2020(Tokyo Olympic Year) We thought we should convert Python2 to Python3 PyCon Taiwan 2017 June 11th
  49. 49. We want to use Python3 We use fabric3 It's fabric for Python3 https://pypi.python.org/pypi/Fabric3 We try to check this, That's good for run PyCon Taiwan 2017 June 11th
  50. 50. We use Python3 & Fabric3 & mypy We use TypeHints for rewriting our code We got it! -> Only 2days We deploy the new version of Out App every week. beta version every day! PyCon Taiwan 2017 June 11th
  51. 51. Those are the Bene ts of Type Hints PyCon Taiwan 2017 June 11th
  52. 52. Today I introduced, and talked about usage and bene ts of Type Hints PyCon Taiwan 2017 June 11th
  53. 53. I hope you can try using Type Hinting from today! PyCon Taiwan 2017 June 11th
  54. 54. Question? PyCon Taiwan 2017 June 11th

×