SlideShare a Scribd company logo
Enjoy Type Hints
and its benefitsPython Conference Hong Kong 2018 Nov 22nd
in Cyberport, Hong Kong
Python Conference Hong Kong 2018 Nov 22nd 1
Python Conference Hong Kong 2018 Nov 22nd 2
Masato Nakamura(masahito)
• work at Nulab inc, Japn. Typetalk team
• use Scala and JavaScript and Python
• Python ❤ and
☕
❤
Python Conference Hong Kong 2018 Nov 22nd 3
Masato Nakamura(masahito)
• Speaker
• Plone Conference 2018 WebDays
• Python Conference Kyushu 2018 in Japan
• Python Conference Taiwan 2017
Python Conference Hong Kong 2018 Nov 22nd 4
Nulab provide collaboration softwares.
Python Conference Hong Kong 2018 Nov 22nd 5
Today's Goal
You can use Type Hints from today!
Python Conference Hong Kong 2018 Nov 22nd 6
Not covering today
Technical Details
Python Conference Hong Kong 2018 Nov 22nd 7
Today's Outline
Ⅰ. Introduction of Type Hints
Ⅱ. Usage of Type Hints
Ⅲ. Benefits of Type Hints
Python Conference Hong Kong 2018 Nov 22nd 8
Today's Outline
!
Ⅰ. Introduction of Type Hints
Ⅱ. Usage of Type Hints
Ⅲ. Benefits of Type Hints
Python Conference Hong Kong 2018 Nov 22nd 9
Introduction of Type Hints
• A. What is Type Hints function
• B. History of Type Hints
• C. typing module
Python Conference Hong Kong 2018 Nov 22nd 10
What is Type Hints function
We can write more Readable Codes.
We can annotate our codes only.
Python Conference Hong Kong 2018 Nov 22nd 11
What is Type Hints function
• Traditional Python code
def twice(num):
return num * 2
• using Type Hints
def twice(num: int) -> int:
return num * 2
Python Conference Hong Kong 2018 Nov 22nd 12
What is Type Hints function
also we can use Class!
class Car:
def __init__(self) -> None:
self.seats = 4
c: Car = Car()
Python Conference Hong Kong 2018 Nov 22nd 13
What is Type Hints function
• using Type Hints
def twice(num: int) -> int:
return num * 2
• C-language Code
int twice(int num) {
return num * 2;
}
Python Conference Hong Kong 2018 Nov 22nd 14
Difference of Type Hints and C code
• If you set wrong Type,We cannot show runtime error
def twice(num: int) -> int:
return num * 2.0
# expected `int` but use `str`
!
print(twice("hello"))
$ python set_wrong_type.py
$ hellohello ##
!
Python Conference Hong Kong 2018 Nov 22nd 15
hmm, What is TypeHints ???
Python Conference Hong Kong 2018 Nov 22nd 16
We can annotate our codes only.
Python Conference Hong Kong 2018 Nov 22nd 17
But You use library, e.g. mypy
$ mypy --python-version 3.7 example.py
example.py:5: error: Argument 1 to "twice" has incompatible type
"str"; expected "int"
Python Conference Hong Kong 2018 Nov 22nd 18
What is good point for checking type ???
Python Conference Hong Kong 2018 Nov 22nd 19
We can check our code without run codes.
• so we can re-write our Python2 code to Python3 more easily
• We can do it !!
Python Conference Hong Kong 2018 Nov 22nd 20
History of Type Hints
Python Conference Hong Kong 2018 Nov 22nd 21
History of Type Hints
implement PEP
Python 3.0 3107
Python 3.5 484
Ptyhon 3.6 526
Python Conference Hong Kong 2018 Nov 22nd 22
Traditional Python code(Python2)
Python 2.x series did not have a way to qualify function arguments
and return values, so many tools and libraries appeared to fill that
gap.
Python Conference Hong Kong 2018 Nov 22nd 23
Traditional Python code(Python2)
def greeting(name):
return 'Hello ' + name
greet = greeting("Masato")
• What is name
!
?
• What does greeting return
!
?
Python Conference Hong Kong 2018 Nov 22nd 24
PEP 3107(Python 3.0)
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 undefined.
Python Conference Hong Kong 2018 Nov 22nd 25
PEP 484(Python 3.5)
There has now been enough 3rd party usage for static type
analysis, that the community would benefit from a standardized
vocabulary and baseline tools within the standard library.
def greeting(name: str) -> str:
return 'Hello ' + name
• PEP-484 Type Hints
Python Conference Hong Kong 2018 Nov 22nd 26
Points in PEP484
Python will remain a dynamically typed language, and the authors
had no desire to ever make type hints mandatory, even by
convention.
• 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 Conference Hong Kong 2018 Nov 22nd 27
inconvinient of 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
Python Conference Hong Kong 2018 Nov 22nd 28
PEP 526(Python 3.6)
# 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!
Python Conference Hong Kong 2018 Nov 22nd 29
typing module
Python Conference Hong Kong 2018 Nov 22nd 30
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
Python Conference Hong Kong 2018 Nov 22nd 31
• 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)
Python Conference Hong Kong 2018 Nov 22nd 32
Today's Outline
Ⅰ. Introduction of Type Hints
!
Ⅱ. Usage of Type Hints
Ⅲ. Benefits of Type Hints
Python Conference Hong Kong 2018 Nov 22nd 33
Usage Of Type Hints
• A. How to write
• B. How to get Type Hints Info
Python Conference Hong Kong 2018 Nov 22nd 34
How to write
PEP526 style
def greeting(name: str) -> str:
return 'Hello ' + name
greet: str = greeting("Masato")
Python Conference Hong Kong 2018 Nov 22nd 35
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
Python Conference Hong Kong 2018 Nov 22nd 36
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
Python Conference Hong Kong 2018 Nov 22nd 37
recommend using Type Hints
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.
Python Conference Hong Kong 2018 Nov 22nd 38
How to get Type Hints Info
Q. where is variable annotation
A. at __annotaitons__
Python Conference Hong Kong 2018 Nov 22nd 39
How to get Type Hints Info
example
>>> answer:int = 42
>>> __annotations__
{'answer': <class 'int'>}
Python Conference Hong Kong 2018 Nov 22nd 40
Note for Class
We can only find 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!
Python Conference Hong Kong 2018 Nov 22nd 41
Today's Outline
Ⅰ. Introduction of Type Hints
Ⅱ. Usage of Type Hints
!
Ⅲ. Benefits of Type Hints
Python Conference Hong Kong 2018 Nov 22nd 42
Benefits of Type Hints
A. Code Style
B. code completion
C. statistic type analysis
D. Our story
Python Conference Hong Kong 2018 Nov 22nd 43
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
Python Conference Hong Kong 2018 Nov 22nd 44
Code Completion
We can use code completion in
• Editor
• Visual Studio code
• IDE
• PyCharm(IntelliJ)
Python Conference Hong Kong 2018 Nov 22nd 45
example
Python Conference Hong Kong 2018 Nov 22nd 46
statistic type analysis
Python Conference Hong Kong 2018 Nov 22nd 47
statistic type analysis
• for check variable type(no runable code)
• python has some tools
• mypy
• pytypes (not talk)
Python Conference Hong Kong 2018 Nov 22nd 48
example
Python Conference Hong Kong 2018 Nov 22nd 49
mypy
• https://github.com/python/mypy
• made by JukkaL & Guido
• can output report
• We can use!(PEP526 style)
Python Conference Hong Kong 2018 Nov 22nd 50
How to install mypy
$ pip install mypy
# if you use Python 2.7 & 3.2-3.4
$ pip install typing
Python Conference Hong Kong 2018 Nov 22nd 51
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"
Python Conference Hong Kong 2018 Nov 22nd 52
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
Python Conference Hong Kong 2018 Nov 22nd 53
Continuous Integration
• Jenkins
• Travis CI
• CircleCi
Python Conference Hong Kong 2018 Nov 22nd 54
Continuous Integration
• we can run mypy on CI systems
• we can get results
• If you develop in a team, there are many benefits
• ex: If someone issues a pull request for your project, you can
review their code
Python Conference Hong Kong 2018 Nov 22nd 55
sample for CI
Sample
Python Conference Hong Kong 2018 Nov 22nd 56
example(error)
Python Conference Hong Kong 2018 Nov 22nd 57
example(success)
Python Conference Hong Kong 2018 Nov 22nd 58
Benefits for us
• We use Fabric for deployment
• But it is for Only Python2
• Python2 will finished at 2020(Tokyo Olympic Year)
• We thought we should convert Python2 to Python3
Python Conference Hong Kong 2018 Nov 22nd 59
Recently, that date has been updated to January 1, 2020.
Python Conference Hong Kong 2018 Nov 22nd 60
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
Python Conference Hong Kong 2018 Nov 22nd 61
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!
Python Conference Hong Kong 2018 Nov 22nd 62
Those are the Benefits of Type Hints
Python Conference Hong Kong 2018 Nov 22nd 63
Today's Outline
✅
1. Introduction of Type Hints
✅
2. Usage of Type Hints
✅
3. Benefits of Type Hints
Python Conference Hong Kong 2018 Nov 22nd 64
I hope you can try using Type
Hinting from today!
Python Conference Hong Kong 2018 Nov 22nd 65
Thank you
@masahito
Python Conference Hong Kong 2018 Nov 22nd 66

More Related Content

What's hot

Python_in_Detail
Python_in_DetailPython_in_Detail
Python_in_Detail
MAHALAKSHMI P
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
Haitham El-Ghareeb
 
Mypy pycon-fi-2012
Mypy pycon-fi-2012Mypy pycon-fi-2012
Mypy pycon-fi-2012
jukkaleh
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
Ishin Vin
 
Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)
IoT Code Lab
 
Functional BDD at Cuke Up
Functional BDD at Cuke UpFunctional BDD at Cuke Up
Functional BDD at Cuke Up
Phillip Trelford
 
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Edureka!
 
Python for Science and Engineering: a presentation to A*STAR and the Singapor...
Python for Science and Engineering: a presentation to A*STAR and the Singapor...Python for Science and Engineering: a presentation to A*STAR and the Singapor...
Python for Science and Engineering: a presentation to A*STAR and the Singapor...
pythoncharmers
 
Python final ppt
Python final pptPython final ppt
Python final ppt
Ripal Ranpara
 
Functional programming-advantages
Functional programming-advantagesFunctional programming-advantages
Functional programming-advantages
Sergei Winitzki
 
James Coplien: Trygve - Oct 17, 2016
James Coplien: Trygve - Oct 17, 2016James Coplien: Trygve - Oct 17, 2016
James Coplien: Trygve - Oct 17, 2016
Foo Café Copenhagen
 
Learning Python - Week 2
Learning Python - Week 2Learning Python - Week 2
Learning Python - Week 2
Mindy McAdams
 
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | EdurekaPython Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Edureka!
 
Python ppt
Python pptPython ppt
Python ppt
Rachit Bhargava
 
Python training
Python trainingPython training
Python training
Kunalchauhan76
 
Python Summer Internship
Python Summer InternshipPython Summer Internship
Python Summer Internship
Atul Kumar
 
Sci py india_conference_2019
Sci py india_conference_2019Sci py india_conference_2019
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
Shivam Gupta
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
Vijay Chaitanya
 

What's hot (19)

Python_in_Detail
Python_in_DetailPython_in_Detail
Python_in_Detail
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Mypy pycon-fi-2012
Mypy pycon-fi-2012Mypy pycon-fi-2012
Mypy pycon-fi-2012
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)
 
Functional BDD at Cuke Up
Functional BDD at Cuke UpFunctional BDD at Cuke Up
Functional BDD at Cuke Up
 
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
 
Python for Science and Engineering: a presentation to A*STAR and the Singapor...
Python for Science and Engineering: a presentation to A*STAR and the Singapor...Python for Science and Engineering: a presentation to A*STAR and the Singapor...
Python for Science and Engineering: a presentation to A*STAR and the Singapor...
 
Python final ppt
Python final pptPython final ppt
Python final ppt
 
Functional programming-advantages
Functional programming-advantagesFunctional programming-advantages
Functional programming-advantages
 
James Coplien: Trygve - Oct 17, 2016
James Coplien: Trygve - Oct 17, 2016James Coplien: Trygve - Oct 17, 2016
James Coplien: Trygve - Oct 17, 2016
 
Learning Python - Week 2
Learning Python - Week 2Learning Python - Week 2
Learning Python - Week 2
 
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | EdurekaPython Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
 
Python ppt
Python pptPython ppt
Python ppt
 
Python training
Python trainingPython training
Python training
 
Python Summer Internship
Python Summer InternshipPython Summer Internship
Python Summer Internship
 
Sci py india_conference_2019
Sci py india_conference_2019Sci py india_conference_2019
Sci py india_conference_2019
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 

Similar to Enjoy Type Hints and its benefits

Python と型ヒントとその使い方
Python と型ヒントとその使い方Python と型ヒントとその使い方
Python と型ヒントとその使い方
masahitojp
 
The Benefits of Type Hints
The Benefits of Type HintsThe Benefits of Type Hints
The Benefits of Type Hints
masahitojp
 
Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!
Andreas Dewes
 
PHYTON-REPORT.pdf
PHYTON-REPORT.pdfPHYTON-REPORT.pdf
PHYTON-REPORT.pdf
PraveenKumar640562
 
unit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptxunit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptx
usvirat1805
 
FDP-faculty deveopmemt program on python
FDP-faculty deveopmemt program on pythonFDP-faculty deveopmemt program on python
FDP-faculty deveopmemt program on python
kannikadg
 
2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english
Jen Yee Hong
 
Python for security professionals by katoh jeremiah [py con ng 2018]
Python for security professionals by katoh jeremiah [py con ng 2018]Python for security professionals by katoh jeremiah [py con ng 2018]
Python for security professionals by katoh jeremiah [py con ng 2018]
jerrykatoh
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
samiwaris2
 
Introduction to python3.pdf
Introduction to python3.pdfIntroduction to python3.pdf
Introduction to python3.pdf
Mohammed Aman Nawaz
 
python programming.pptx
python programming.pptxpython programming.pptx
python programming.pptx
Kaviya452563
 
Python Introduction its a oop language and easy to use
Python Introduction its a oop language and easy to usePython Introduction its a oop language and easy to use
Python Introduction its a oop language and easy to use
SrajanCollege1
 
CrashCourse: Python with DataCamp and Jupyter for Beginners
CrashCourse: Python with DataCamp and Jupyter for BeginnersCrashCourse: Python with DataCamp and Jupyter for Beginners
CrashCourse: Python with DataCamp and Jupyter for Beginners
Olga Scrivner
 
Algorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to AlgorithmsAlgorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to Algorithms
Mohamed Loey
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
gabriellekuruvilla
 
Python typing module
Python typing modulePython typing module
Python typing module
Ryan Blunden
 
Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data science
deepak teja
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
Bhavsingh Maloth
 
A Data Science Tutorial in Python
A Data Science Tutorial in PythonA Data Science Tutorial in Python
A Data Science Tutorial in Python
Ajay Ohri
 
Introduction to Python programming Language
Introduction to Python programming LanguageIntroduction to Python programming Language
Introduction to Python programming Language
MansiSuthar3
 

Similar to Enjoy Type Hints and its benefits (20)

Python と型ヒントとその使い方
Python と型ヒントとその使い方Python と型ヒントとその使い方
Python と型ヒントとその使い方
 
The Benefits of Type Hints
The Benefits of Type HintsThe Benefits of Type Hints
The Benefits of Type Hints
 
Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!
 
PHYTON-REPORT.pdf
PHYTON-REPORT.pdfPHYTON-REPORT.pdf
PHYTON-REPORT.pdf
 
unit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptxunit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptx
 
FDP-faculty deveopmemt program on python
FDP-faculty deveopmemt program on pythonFDP-faculty deveopmemt program on python
FDP-faculty deveopmemt program on python
 
2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english
 
Python for security professionals by katoh jeremiah [py con ng 2018]
Python for security professionals by katoh jeremiah [py con ng 2018]Python for security professionals by katoh jeremiah [py con ng 2018]
Python for security professionals by katoh jeremiah [py con ng 2018]
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
Introduction to python3.pdf
Introduction to python3.pdfIntroduction to python3.pdf
Introduction to python3.pdf
 
python programming.pptx
python programming.pptxpython programming.pptx
python programming.pptx
 
Python Introduction its a oop language and easy to use
Python Introduction its a oop language and easy to usePython Introduction its a oop language and easy to use
Python Introduction its a oop language and easy to use
 
CrashCourse: Python with DataCamp and Jupyter for Beginners
CrashCourse: Python with DataCamp and Jupyter for BeginnersCrashCourse: Python with DataCamp and Jupyter for Beginners
CrashCourse: Python with DataCamp and Jupyter for Beginners
 
Algorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to AlgorithmsAlgorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to Algorithms
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
 
Python typing module
Python typing modulePython typing module
Python typing module
 
Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data science
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
A Data Science Tutorial in Python
A Data Science Tutorial in PythonA Data Science Tutorial in Python
A Data Science Tutorial in Python
 
Introduction to Python programming Language
Introduction to Python programming LanguageIntroduction to Python programming Language
Introduction to Python programming Language
 

More from masahitojp

Build a RESTful API with the Serverless Framework
Build a RESTful API with the Serverless FrameworkBuild a RESTful API with the Serverless Framework
Build a RESTful API with the Serverless Framework
masahitojp
 
Presentation kyushu-2018
Presentation kyushu-2018Presentation kyushu-2018
Presentation kyushu-2018
masahitojp
 
serverless framework + AWS Lambda with Python
serverless framework + AWS Lambda with Pythonserverless framework + AWS Lambda with Python
serverless framework + AWS Lambda with Python
masahitojp
 
20170131 python3 6 PEP526
20170131 python3 6 PEP526 20170131 python3 6 PEP526
20170131 python3 6 PEP526
masahitojp
 
chat bot framework for Java8
chat bot framework for Java8chat bot framework for Java8
chat bot framework for Java8
masahitojp
 
Akka meetup 2014_sep
Akka meetup 2014_sepAkka meetup 2014_sep
Akka meetup 2014_sep
masahitojp
 
Pyconjp2014_implementations
Pyconjp2014_implementationsPyconjp2014_implementations
Pyconjp2014_implementations
masahitojp
 
Pyconsg2014 pyston
Pyconsg2014 pystonPyconsg2014 pyston
Pyconsg2014 pyston
masahitojp
 
Riak map reduce for beginners
Riak map reduce for beginnersRiak map reduce for beginners
Riak map reduce for beginners
masahitojp
 
Play2 translate 20120714
Play2 translate 20120714Play2 translate 20120714
Play2 translate 20120714masahitojp
 
Play2の裏側
Play2の裏側Play2の裏側
Play2の裏側masahitojp
 
Play!framework2.0 introduction
Play!framework2.0 introductionPlay!framework2.0 introduction
Play!framework2.0 introduction
masahitojp
 
5分で説明する Play! scala
5分で説明する Play! scala5分で説明する Play! scala
5分で説明する Play! scala
masahitojp
 

More from masahitojp (14)

Build a RESTful API with the Serverless Framework
Build a RESTful API with the Serverless FrameworkBuild a RESTful API with the Serverless Framework
Build a RESTful API with the Serverless Framework
 
Presentation kyushu-2018
Presentation kyushu-2018Presentation kyushu-2018
Presentation kyushu-2018
 
serverless framework + AWS Lambda with Python
serverless framework + AWS Lambda with Pythonserverless framework + AWS Lambda with Python
serverless framework + AWS Lambda with Python
 
20170131 python3 6 PEP526
20170131 python3 6 PEP526 20170131 python3 6 PEP526
20170131 python3 6 PEP526
 
chat bot framework for Java8
chat bot framework for Java8chat bot framework for Java8
chat bot framework for Java8
 
Akka meetup 2014_sep
Akka meetup 2014_sepAkka meetup 2014_sep
Akka meetup 2014_sep
 
Pyconjp2014_implementations
Pyconjp2014_implementationsPyconjp2014_implementations
Pyconjp2014_implementations
 
Pyconsg2014 pyston
Pyconsg2014 pystonPyconsg2014 pyston
Pyconsg2014 pyston
 
Pykonjp2014
Pykonjp2014Pykonjp2014
Pykonjp2014
 
Riak map reduce for beginners
Riak map reduce for beginnersRiak map reduce for beginners
Riak map reduce for beginners
 
Play2 translate 20120714
Play2 translate 20120714Play2 translate 20120714
Play2 translate 20120714
 
Play2の裏側
Play2の裏側Play2の裏側
Play2の裏側
 
Play!framework2.0 introduction
Play!framework2.0 introductionPlay!framework2.0 introduction
Play!framework2.0 introduction
 
5分で説明する Play! scala
5分で説明する Play! scala5分で説明する Play! scala
5分で説明する Play! scala
 

Recently uploaded

Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEMTIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
HODECEDSIET
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
Rahul
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
NazakatAliKhoso2
 
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
University of Maribor
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
IJNSA Journal
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
Engine Lubrication performance System.pdf
Engine Lubrication performance System.pdfEngine Lubrication performance System.pdf
Engine Lubrication performance System.pdf
mamamaam477
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
KrishnaveniKrishnara1
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
NidhalKahouli2
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
IJECEIAES
 

Recently uploaded (20)

Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEMTIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
 
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
Engine Lubrication performance System.pdf
Engine Lubrication performance System.pdfEngine Lubrication performance System.pdf
Engine Lubrication performance System.pdf
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
 

Enjoy Type Hints and its benefits

  • 1. Enjoy Type Hints and its benefitsPython Conference Hong Kong 2018 Nov 22nd in Cyberport, Hong Kong Python Conference Hong Kong 2018 Nov 22nd 1
  • 2. Python Conference Hong Kong 2018 Nov 22nd 2
  • 3. Masato Nakamura(masahito) • work at Nulab inc, Japn. Typetalk team • use Scala and JavaScript and Python • Python ❤ and ☕ ❤ Python Conference Hong Kong 2018 Nov 22nd 3
  • 4. Masato Nakamura(masahito) • Speaker • Plone Conference 2018 WebDays • Python Conference Kyushu 2018 in Japan • Python Conference Taiwan 2017 Python Conference Hong Kong 2018 Nov 22nd 4
  • 5. Nulab provide collaboration softwares. Python Conference Hong Kong 2018 Nov 22nd 5
  • 6. Today's Goal You can use Type Hints from today! Python Conference Hong Kong 2018 Nov 22nd 6
  • 7. Not covering today Technical Details Python Conference Hong Kong 2018 Nov 22nd 7
  • 8. Today's Outline Ⅰ. Introduction of Type Hints Ⅱ. Usage of Type Hints Ⅲ. Benefits of Type Hints Python Conference Hong Kong 2018 Nov 22nd 8
  • 9. Today's Outline ! Ⅰ. Introduction of Type Hints Ⅱ. Usage of Type Hints Ⅲ. Benefits of Type Hints Python Conference Hong Kong 2018 Nov 22nd 9
  • 10. Introduction of Type Hints • A. What is Type Hints function • B. History of Type Hints • C. typing module Python Conference Hong Kong 2018 Nov 22nd 10
  • 11. What is Type Hints function We can write more Readable Codes. We can annotate our codes only. Python Conference Hong Kong 2018 Nov 22nd 11
  • 12. What is Type Hints function • Traditional Python code def twice(num): return num * 2 • using Type Hints def twice(num: int) -> int: return num * 2 Python Conference Hong Kong 2018 Nov 22nd 12
  • 13. What is Type Hints function also we can use Class! class Car: def __init__(self) -> None: self.seats = 4 c: Car = Car() Python Conference Hong Kong 2018 Nov 22nd 13
  • 14. What is Type Hints function • using Type Hints def twice(num: int) -> int: return num * 2 • C-language Code int twice(int num) { return num * 2; } Python Conference Hong Kong 2018 Nov 22nd 14
  • 15. Difference of Type Hints and C code • If you set wrong Type,We cannot show runtime error def twice(num: int) -> int: return num * 2.0 # expected `int` but use `str` ! print(twice("hello")) $ python set_wrong_type.py $ hellohello ## ! Python Conference Hong Kong 2018 Nov 22nd 15
  • 16. hmm, What is TypeHints ??? Python Conference Hong Kong 2018 Nov 22nd 16
  • 17. We can annotate our codes only. Python Conference Hong Kong 2018 Nov 22nd 17
  • 18. But You use library, e.g. mypy $ mypy --python-version 3.7 example.py example.py:5: error: Argument 1 to "twice" has incompatible type "str"; expected "int" Python Conference Hong Kong 2018 Nov 22nd 18
  • 19. What is good point for checking type ??? Python Conference Hong Kong 2018 Nov 22nd 19
  • 20. We can check our code without run codes. • so we can re-write our Python2 code to Python3 more easily • We can do it !! Python Conference Hong Kong 2018 Nov 22nd 20
  • 21. History of Type Hints Python Conference Hong Kong 2018 Nov 22nd 21
  • 22. History of Type Hints implement PEP Python 3.0 3107 Python 3.5 484 Ptyhon 3.6 526 Python Conference Hong Kong 2018 Nov 22nd 22
  • 23. Traditional Python code(Python2) Python 2.x series did not have a way to qualify function arguments and return values, so many tools and libraries appeared to fill that gap. Python Conference Hong Kong 2018 Nov 22nd 23
  • 24. Traditional Python code(Python2) def greeting(name): return 'Hello ' + name greet = greeting("Masato") • What is name ! ? • What does greeting return ! ? Python Conference Hong Kong 2018 Nov 22nd 24
  • 25. PEP 3107(Python 3.0) 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 undefined. Python Conference Hong Kong 2018 Nov 22nd 25
  • 26. PEP 484(Python 3.5) There has now been enough 3rd party usage for static type analysis, that the community would benefit from a standardized vocabulary and baseline tools within the standard library. def greeting(name: str) -> str: return 'Hello ' + name • PEP-484 Type Hints Python Conference Hong Kong 2018 Nov 22nd 26
  • 27. Points in PEP484 Python will remain a dynamically typed language, and the authors had no desire to ever make type hints mandatory, even by convention. • 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 Conference Hong Kong 2018 Nov 22nd 27
  • 28. inconvinient of 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 Python Conference Hong Kong 2018 Nov 22nd 28
  • 29. PEP 526(Python 3.6) # 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! Python Conference Hong Kong 2018 Nov 22nd 29
  • 30. typing module Python Conference Hong Kong 2018 Nov 22nd 30
  • 31. 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 Python Conference Hong Kong 2018 Nov 22nd 31
  • 32. • 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) Python Conference Hong Kong 2018 Nov 22nd 32
  • 33. Today's Outline Ⅰ. Introduction of Type Hints ! Ⅱ. Usage of Type Hints Ⅲ. Benefits of Type Hints Python Conference Hong Kong 2018 Nov 22nd 33
  • 34. Usage Of Type Hints • A. How to write • B. How to get Type Hints Info Python Conference Hong Kong 2018 Nov 22nd 34
  • 35. How to write PEP526 style def greeting(name: str) -> str: return 'Hello ' + name greet: str = greeting("Masato") Python Conference Hong Kong 2018 Nov 22nd 35
  • 36. 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 Python Conference Hong Kong 2018 Nov 22nd 36
  • 37. 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 Python Conference Hong Kong 2018 Nov 22nd 37
  • 38. recommend using Type Hints 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. Python Conference Hong Kong 2018 Nov 22nd 38
  • 39. How to get Type Hints Info Q. where is variable annotation A. at __annotaitons__ Python Conference Hong Kong 2018 Nov 22nd 39
  • 40. How to get Type Hints Info example >>> answer:int = 42 >>> __annotations__ {'answer': <class 'int'>} Python Conference Hong Kong 2018 Nov 22nd 40
  • 41. Note for Class We can only find 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! Python Conference Hong Kong 2018 Nov 22nd 41
  • 42. Today's Outline Ⅰ. Introduction of Type Hints Ⅱ. Usage of Type Hints ! Ⅲ. Benefits of Type Hints Python Conference Hong Kong 2018 Nov 22nd 42
  • 43. Benefits of Type Hints A. Code Style B. code completion C. statistic type analysis D. Our story Python Conference Hong Kong 2018 Nov 22nd 43
  • 44. 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 Python Conference Hong Kong 2018 Nov 22nd 44
  • 45. Code Completion We can use code completion in • Editor • Visual Studio code • IDE • PyCharm(IntelliJ) Python Conference Hong Kong 2018 Nov 22nd 45
  • 46. example Python Conference Hong Kong 2018 Nov 22nd 46
  • 47. statistic type analysis Python Conference Hong Kong 2018 Nov 22nd 47
  • 48. statistic type analysis • for check variable type(no runable code) • python has some tools • mypy • pytypes (not talk) Python Conference Hong Kong 2018 Nov 22nd 48
  • 49. example Python Conference Hong Kong 2018 Nov 22nd 49
  • 50. mypy • https://github.com/python/mypy • made by JukkaL & Guido • can output report • We can use!(PEP526 style) Python Conference Hong Kong 2018 Nov 22nd 50
  • 51. How to install mypy $ pip install mypy # if you use Python 2.7 & 3.2-3.4 $ pip install typing Python Conference Hong Kong 2018 Nov 22nd 51
  • 52. 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" Python Conference Hong Kong 2018 Nov 22nd 52
  • 53. 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 Python Conference Hong Kong 2018 Nov 22nd 53
  • 54. Continuous Integration • Jenkins • Travis CI • CircleCi Python Conference Hong Kong 2018 Nov 22nd 54
  • 55. Continuous Integration • we can run mypy on CI systems • we can get results • If you develop in a team, there are many benefits • ex: If someone issues a pull request for your project, you can review their code Python Conference Hong Kong 2018 Nov 22nd 55
  • 56. sample for CI Sample Python Conference Hong Kong 2018 Nov 22nd 56
  • 57. example(error) Python Conference Hong Kong 2018 Nov 22nd 57
  • 59. Benefits for us • We use Fabric for deployment • But it is for Only Python2 • Python2 will finished at 2020(Tokyo Olympic Year) • We thought we should convert Python2 to Python3 Python Conference Hong Kong 2018 Nov 22nd 59
  • 60. Recently, that date has been updated to January 1, 2020. Python Conference Hong Kong 2018 Nov 22nd 60
  • 61. 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 Python Conference Hong Kong 2018 Nov 22nd 61
  • 62. 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! Python Conference Hong Kong 2018 Nov 22nd 62
  • 63. Those are the Benefits of Type Hints Python Conference Hong Kong 2018 Nov 22nd 63
  • 64. Today's Outline ✅ 1. Introduction of Type Hints ✅ 2. Usage of Type Hints ✅ 3. Benefits of Type Hints Python Conference Hong Kong 2018 Nov 22nd 64
  • 65. I hope you can try using Type Hinting from today! Python Conference Hong Kong 2018 Nov 22nd 65
  • 66. Thank you @masahito Python Conference Hong Kong 2018 Nov 22nd 66