SlideShare ist ein Scribd-Unternehmen logo
1 von 54
Downloaden Sie, um offline zu lesen
The Bene ts of Type Hints
PyCon Taiwan 2017 June 11th 1
Masato Nakamura(中村真人) from
Nulab Japan
PyCon Taiwan 2017 June 11th
What is Nulab
PyCon Taiwan 2017 June 11th
We provide Collaboration software.
PyCon Taiwan 2017 June 11th
My Goal
You can use Type Hints from today!
PyCon Taiwan 2017 June 11th
Not covering today
Technical Details
PyCon Taiwan 2017 June 11th
Today I will introduce, and talk about
the Usage and Bene ts of Type Hints
PyCon Taiwan 2017 June 11th
Introduction
PyCon Taiwan 2017 June 11th
Introduction
What are Type Hints
Hisory
typing module
PyCon Taiwan 2017 June 11th
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
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
History
PyCon Taiwan 2017 June 11th
History
Type Hints has a three-part history.
PyCon Taiwan 2017 June 11th
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
History
PEP implement
3107 Python 3.0
484 Python 3.5
526 Ptyhon 3.6
PyCon Taiwan 2017 June 11th
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
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
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
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
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
typing module
PyCon Taiwan 2017 June 11th
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
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
Usage
PyCon Taiwan 2017 June 11th
Usage
How to write
How to get Type Hints Info
PyCon Taiwan 2017 June 11th
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
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
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
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
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
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
Bene ts
PyCon Taiwan 2017 June 11th
Bene ts
Code Style
code completion
statistic type analysis
Our story
PyCon Taiwan 2017 June 11th
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
Code Completion
We can use code completion in
Editor
Visual Studio code
PyCharm(IntelliJ)
PyCon Taiwan 2017 June 11th
example
PyCon Taiwan 2017 June 11th
statistic type analysis
PyCon Taiwan 2017 June 11th
statistic type analysis
for check variable type(no runable code)
python has some tools
mypy
pytypes (not talk)
PyCon Taiwan 2017 June 11th
example
PyCon Taiwan 2017 June 11th
mypy
https://github.com/python/mypy
made by JukkaL & Guido
can output report
We can use!(PEP526 style)
PyCon Taiwan 2017 June 11th
mypy
$ pip install mypy
# if you use Python 2.7 & 3.2-3.4
$ pip install typing
PyCon Taiwan 2017 June 11th
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
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
Continuous Integration
Jenkins
Github + Travis CI
Github + CircleCi
PyCon Taiwan 2017 June 11th
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
example(error)
PyCon Taiwan 2017 June 11th
example(success)
PyCon Taiwan 2017 June 11th
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
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
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
Those are the Bene ts of Type Hints
PyCon Taiwan 2017 June 11th
Today I introduced, and talked about
usage and bene ts of Type Hints
PyCon Taiwan 2017 June 11th
I hope you can try using Type Hinting
from today!
PyCon Taiwan 2017 June 11th
Question?
PyCon Taiwan 2017 June 11th

Weitere ähnliche Inhalte

Was ist angesagt?

Python Developer Certification
Python Developer CertificationPython Developer Certification
Python Developer CertificationVskills
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Chariza Pladin
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MoreMatt Harrison
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)Matt Harrison
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.Mosky Liu
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introductionstn_tkiller
 
Learning Python - Week 2
Learning Python - Week 2Learning Python - Week 2
Learning Python - Week 2Mindy McAdams
 
Introduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data AnalyticsIntroduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data AnalyticsPhoenix
 
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
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAMaulik Borsaniya
 
Python interview question for students
Python interview question for studentsPython interview question for students
Python interview question for studentsCorey McCreary
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 

Was ist angesagt? (19)

Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
 
Python Developer Certification
Python Developer CertificationPython Developer Certification
Python Developer Certification
 
Python Workshop
Python WorkshopPython Workshop
Python Workshop
 
Python Presentation
Python PresentationPython Presentation
Python Presentation
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.
 
Python Workshop
Python WorkshopPython Workshop
Python Workshop
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introduction
 
Python ppt
Python pptPython ppt
Python ppt
 
Learning Python - Week 2
Learning Python - Week 2Learning Python - Week 2
Learning Python - Week 2
 
Introduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data AnalyticsIntroduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data Analytics
 
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)
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
 
Python interview question for students
Python interview question for studentsPython interview question for students
Python interview question for students
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Python basics
Python basicsPython basics
Python basics
 
Python basic
Python basicPython basic
Python basic
 

Ähnlich wie The Benefits of Type Hints

Enjoy Type Hints and its benefits
Enjoy Type Hints and its benefitsEnjoy Type Hints and its benefits
Enjoy Type Hints and its benefitsmasahitojp
 
Python と型ヒントとその使い方
Python と型ヒントとその使い方Python と型ヒントとその使い方
Python と型ヒントとその使い方masahitojp
 
Python PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptxPython PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptxsushil155005
 
Python Basics
Python BasicsPython Basics
Python BasicsPooja B S
 
Python03 course in_mumbai
Python03 course in_mumbaiPython03 course in_mumbai
Python03 course in_mumbaivibrantuser
 
FDP-faculty deveopmemt program on python
FDP-faculty deveopmemt program on pythonFDP-faculty deveopmemt program on python
FDP-faculty deveopmemt program on pythonkannikadg
 
R and Python, A Code Demo
R and Python, A Code DemoR and Python, A Code Demo
R and Python, A Code DemoVineet Jaiswal
 
Python programming msc(cs)
Python programming msc(cs)Python programming msc(cs)
Python programming msc(cs)KALAISELVI P
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1Abdul Haseeb
 
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.pptxusvirat1805
 
AmI 2017 - Python basics
AmI 2017 - Python basicsAmI 2017 - Python basics
AmI 2017 - Python basicsLuigi De Russis
 
Python Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdfPython Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdfSreedhar Chowdam
 
IT talk "Python language evolution"
IT talk "Python language evolution"IT talk "Python language evolution"
IT talk "Python language evolution"DataArt
 
Python for R developers and data scientists
Python for R developers and data scientistsPython for R developers and data scientists
Python for R developers and data scientistsLambda Tree
 
型ヒントについて考えよう!
型ヒントについて考えよう!型ヒントについて考えよう!
型ヒントについて考えよう!Yusuke Miyazaki
 

Ähnlich wie The Benefits of Type Hints (20)

Enjoy Type Hints and its benefits
Enjoy Type Hints and its benefitsEnjoy Type Hints and its benefits
Enjoy Type Hints and its benefits
 
Python と型ヒントとその使い方
Python と型ヒントとその使い方Python と型ヒントとその使い方
Python と型ヒントとその使い方
 
Python PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptxPython PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptx
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Python03 course in_mumbai
Python03 course in_mumbaiPython03 course in_mumbai
Python03 course in_mumbai
 
PEP 498: The Monologue
PEP 498: The MonologuePEP 498: The Monologue
PEP 498: The Monologue
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
FDP-faculty deveopmemt program on python
FDP-faculty deveopmemt program on pythonFDP-faculty deveopmemt program on python
FDP-faculty deveopmemt program on python
 
R and Python, A Code Demo
R and Python, A Code DemoR and Python, A Code Demo
R and Python, A Code Demo
 
Python programming msc(cs)
Python programming msc(cs)Python programming msc(cs)
Python programming msc(cs)
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
 
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
 
AmI 2017 - Python basics
AmI 2017 - Python basicsAmI 2017 - Python basics
AmI 2017 - Python basics
 
Python Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdfPython Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdf
 
Intro
IntroIntro
Intro
 
IT talk "Python language evolution"
IT talk "Python language evolution"IT talk "Python language evolution"
IT talk "Python language evolution"
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Python for R developers and data scientists
Python for R developers and data scientistsPython for R developers and data scientists
Python for R developers and data scientists
 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
 
型ヒントについて考えよう!
型ヒントについて考えよう!型ヒントについて考えよう!
型ヒントについて考えよう!
 

Mehr von 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 Frameworkmasahitojp
 
Presentation kyushu-2018
Presentation kyushu-2018Presentation kyushu-2018
Presentation kyushu-2018masahitojp
 
serverless framework + AWS Lambda with Python
serverless framework + AWS Lambda with Pythonserverless framework + AWS Lambda with Python
serverless framework + AWS Lambda with Pythonmasahitojp
 
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 Java8masahitojp
 
Akka meetup 2014_sep
Akka meetup 2014_sepAkka meetup 2014_sep
Akka meetup 2014_sepmasahitojp
 
Pyconjp2014_implementations
Pyconjp2014_implementationsPyconjp2014_implementations
Pyconjp2014_implementationsmasahitojp
 
Pyconsg2014 pyston
Pyconsg2014 pystonPyconsg2014 pyston
Pyconsg2014 pystonmasahitojp
 
Riak map reduce for beginners
Riak map reduce for beginnersRiak map reduce for beginners
Riak map reduce for beginnersmasahitojp
 
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 introductionmasahitojp
 
5分で説明する Play! scala
5分で説明する Play! scala5分で説明する Play! scala
5分で説明する Play! scalamasahitojp
 

Mehr von 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
 

Kürzlich hochgeladen

Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdfKamal Acharya
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...drmkjayanthikannan
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...Amil baba
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesRAJNEESHKUMAR341697
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdfKamal Acharya
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesMayuraD1
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxMuhammadAsimMuhammad6
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationBhangaleSonal
 
Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilVinayVitekari
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 

Kürzlich hochgeladen (20)

Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech Civil
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 

The Benefits of Type Hints

  • 1. The Bene ts of Type Hints PyCon Taiwan 2017 June 11th 1
  • 2. Masato Nakamura(中村真人) from Nulab Japan PyCon Taiwan 2017 June 11th
  • 3. What is Nulab PyCon Taiwan 2017 June 11th
  • 4. We provide Collaboration software. PyCon Taiwan 2017 June 11th
  • 5. My Goal You can use Type Hints from today! PyCon Taiwan 2017 June 11th
  • 6. Not covering today Technical Details PyCon Taiwan 2017 June 11th
  • 7. Today I will introduce, and talk about the Usage and Bene ts of Type Hints PyCon Taiwan 2017 June 11th
  • 9. Introduction What are Type Hints Hisory typing module PyCon Taiwan 2017 June 11th
  • 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. 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
  • 13. History Type Hints has a three-part history. PyCon Taiwan 2017 June 11th
  • 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. History PEP implement 3107 Python 3.0 484 Python 3.5 526 Ptyhon 3.6 PyCon Taiwan 2017 June 11th
  • 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. 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. 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. 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. 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. typing module PyCon Taiwan 2017 June 11th
  • 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. 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
  • 25. Usage How to write How to get Type Hints Info PyCon Taiwan 2017 June 11th
  • 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. 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. 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. 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. 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. 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. Bene ts PyCon Taiwan 2017 June 11th
  • 33. Bene ts Code Style code completion statistic type analysis Our story PyCon Taiwan 2017 June 11th
  • 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. Code Completion We can use code completion in Editor Visual Studio code PyCharm(IntelliJ) PyCon Taiwan 2017 June 11th
  • 37. statistic type analysis PyCon Taiwan 2017 June 11th
  • 38. statistic type analysis for check variable type(no runable code) python has some tools mypy pytypes (not talk) PyCon Taiwan 2017 June 11th
  • 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. mypy $ pip install mypy # if you use Python 2.7 & 3.2-3.4 $ pip install typing PyCon Taiwan 2017 June 11th
  • 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. 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. Continuous Integration Jenkins Github + Travis CI Github + CircleCi PyCon Taiwan 2017 June 11th
  • 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
  • 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. 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. 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. Those are the Bene ts of Type Hints PyCon Taiwan 2017 June 11th
  • 52. Today I introduced, and talked about usage and bene ts of Type Hints PyCon Taiwan 2017 June 11th
  • 53. I hope you can try using Type Hinting from today! PyCon Taiwan 2017 June 11th