Oursky Code
  • AI
  • Auth
  • More from Oursky
    • Oursky Business Blog
    • GitHub
    • About Us
  • AI
  • Auth
  • More from Oursky
0
Subscribe
Oursky Code
Oursky Code
  • AI
  • Auth
  • More from Oursky
    • Oursky Business Blog
    • GitHub
    • About Us
  • Python

Type Hints – Better type at Python

  • December 16, 2015
  • No comments
  • 3 minute read
  • Rick Mak
Type Hints – Better type at Python
Type Hints – Better type at Python
Total
30
Shares
30
0
0

Python is known as a dynamic, (https://wiki.python.org/moin/Why is Python a dynamic language and also a strongly typed language) language. Most developers love it but some feel mad without type checking or type-hinted auto-completion. In Python3.5, Type Hints is introduced to further delight developers who want those features.

Type Hints offers type checking on function parameters, return values and class attributes, as if it’s static-typed. If you pass something does not match the expected type, a warning will be given.

According to The Theory of Type Hints, here’s an example showing how the rules work out in practice:

Say there is an Employee class, and a subclass Manager:

class Employee:
    pass

class Manager(Employee):
    pass

Let’s say variable e is declared with type Employee:

e = Employee() # type: Employee

Now it’s OK to assign a Manager instance to e:

e = Manager()

It’s not OK to assign an Employee instance to a variable declared with type Manager:

m = Manager() # type: Manager

m = Employee() # Fails static check

Now, suppose we have a variable whose type is Any:

a = some_func() # type: Any

It’s OK to assign a to Employee e:

e = a # OK

Of course it’s also OK to assign Employee e to a:

a = e # OK

Benefits

By introducing Type Hints in Python, it makes Python even more friendly to programmers. At least it helps prevents premature-idiot bugs regarding type errors. And there are more benefits we might consider:

Make IDE to work better

IDE like PyCharm can perform type checking on variable assignments and return values in local functions. Since type information is crucial for static code analysis, this also make code completion easier.

pycharm
Warning on wrong type – PyCharm

Improve code readabilty

We often emphasize Code as documentation. Type Hints makes code more readable to both human and tools. Let’s spend less time to figure out what type to pass and return as the information is clearly written in the func type annotation.

Serve as Documentation

Now you can get rid of specifying argument types in the wordy docs. Some documentation generation tool like Sphinx reads Type Hints annotation as information.

Previously:

def hello(name='nobody'):
    """Say hello to a person

    :param name: string value
    :rtype: string value
    """
    return 'Hello' + name

with Type Hints:

def hello(name: str = 'nobody') -> str:
    '''Say hello to a person
    '''
    return 'Hello' + name

What Type Hints is NOT

Type Hints works on code level and involves syntax, yet it is not about the followings:

It’s not about code generation

It’s not going to affect how your compiler complies your code.

It’s not going to fix all code issues

Your code can still break during run time after type checking.

It’s not about runtime type checking, nor performance overhead

Since there’s no effect on the compiled code, you won’t get a faster nor slower program with Type Hints on.

It’s not going to make Python static-typed

This might be concerned by Python-lovers. In PEP-0484, the authors put the following disclaimer to clam the over-reacted Python fans:

It should also be emphasized that Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention.

Those who worried about Python will be made static-typed can now relax 🙂

When using Type Hints

To use the max power of Type Hints, take this piece of advice:

“Be liberal in what you accept, and conservative in what you return”

Example:

from typing import Iterable, List

def even(numbers: Iterable) -> List:
    return list(n for n in numbers if n % 2 == 0)

Get Type Hints in your Python

For Python 3.5

just import typing

For Python 3.2 – 3.4

you will need to pip install typing before importing

For Python2

you can enable type checking with pyi stub: python/typeshed

More

  • How You Can Benefit from Type Hints – Andrey Vlasovskikh JetBrains
  • Better type at Python – Rick Mak
  • mypy – an experimental optional static type checker for Python
  • Guido van Rossum – Type Hints for Python 3.5
  • PEP483 – The Theory of Type Hints

Read more from Oursky

Total
30
Shares
Share 30
Tweet 0
Pin it 0
Related Topics
  • Dev
  • python
  • python3
  • typehints
  • web
Rick Mak

Previous Article
Top 10 Mobile App UX Design Mistakes
  • Android
  • iOS
  • UX/UI Design

Top 10 Mobile App UX Design Mistakes

  • November 24, 2015
  • Joyz Ng
View Post
Next Article
  • Android
  • iOS
  • Software Testing

Journey Through Agile Test Automation

  • May 6, 2016
  • Joyz Ng
View Post
You May Also Like
pixabay ai tensorflow post
View Post
  • Artificial Intelligence
  • Python

Using Tensorflow and Support Vector Machine to Create an Image Classifications Engine

  • October 21, 2016
  • May Yeung
View Post
  • DevOps
  • Python

Dockerizing our Python stack

  • September 1, 2015
  • Rick Mak
View Post
  • Python

SQLAlchemy in batches: Generating a top playlist

  • June 19, 2015
  • Kenji Pa

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Subscribe Us

Join our mailing list to never miss an update!

Oursky Code Blog
A team of Developers, Designers and Geeks. All about hacking and building things.

Input your search keywords and press Enter.