Type Hints in Python

Type Hints in Python is another important parameter used by different programmers in performing different tasks. Learn more about it here.

Type Hints in Python: Adding types to a function

Let’s take an example of a function which receives two arguments and returns a value indicating their sum:

def two_sum(a, b):
return a + b

By looking at this code, one can not safely and without doubt indicate the type of the arguments for function two_sum. It works both when supplied with int values:

print(two_sum(2, 1)) # result: 3

and with strings:

print(two_sum("a", "b")) # result: "ab"

and with other values, such as lists, tuples et cetera.

Due to this dynamic nature of python types, where many are applicable for a given operation, any type checker would not be able to reasonably assert whether a call for this function should be allowed or not.

To assist our type checker we can now provide type hints for it in the Function definition indicating the type that we allow.

To indicate that we only want to allow int types we can change our function definition to look like:

def two_sum(a: int, b: int):
return a + b

Annotations follow the argument name and are separated by a : character.

Similarly, to indicate only str types are allowed, we’d change our function to specify it:

def two_sum(a: str, b: str):
return a + b

Apart from specifying the type of the arguments, one could also indicate the return value of a function call. This is done by adding the -> character followed by the type after the closing parenthesis in the argument list but before the : at the end of the function declaration:

def two_sum(a: int, b: int) -> int:
return a + b

Now we’ve indicated that the return value when calling two_sum should be of type int. Similarly we can define appropriate values for str, float, list, set and others.

Although type hints are mostly used by type checkers and IDEs, sometimes you may need to retrieve them. This can be done using the annotations special attribute:

two_sum.annotations

{‘a’: , ‘b’: , ‘return’: }

Type Hints in Python: NamedTuple

Creating a namedtuple with type hints is done using the function NamedTuple from the typing module:

import typing
Point = typing.NamedTuple('Point', [('x', int), ('y', int)])

Note that the name of the resulting type is the first argument to the function, but it should be assigned to a variable with the same name to ease the work of type checkers.

Generic Types

The typing.TypeVar is a generic type factory. It’s primary goal is to serve as a parameter/placeholder for generic function/class/method annotations:

import typing
T = typing.TypeVar("T")
def get_first_element(l: typing.Sequence[T]) -> T:
"""Gets the first element of a sequence."""
return l[0]

Variables and Attributes

Variables are annotated using comments:

x = 3 # type: int
x = negate(x)
x = 'a type-checker might catch this error'

Python 3.x Version ≥ 3.6

Starting from Python 3.6, there is also new syntax for variable annotations. The code above might use the form

int = 3

Unlike with comments, it is also possible to just add a type hint to a variable that was not previously declared, without setting a value to it:

int

Additionally if these are used in the module or the class level, the type hints can be retrieved using typing.get_type_hints(class_or_module):

class Foo:
int
str = 'abc'
print(typing.get_type_hints(Foo))

ChainMap({‘x’: , ‘y’: }, {})

Alternatively, they can be accessed by using the annotations special variable or attribute:

int
print(annotations)

{‘x’: }

class C:
str
print(C.annotations)

{‘s’: }

Class Members and Methods

class A:
x = None # type: float
def init(self, x: float) -> None:
"""
self should not be annotated
init should be annotated to return None
"""
self.x = x
@classmethod
def from_int(cls, x: int) -> 'A':
"""
cls should not be annotated
Use forward reference to refer to current class with string literal 'A'
"""
return cls(float(x))

Forward reference of the current class is needed since annotations are evaluated when the function is defined.

Forward references can also be used when referring to a class that would cause a circular import if imported.

Type Hints in Python: Type hints for keyword arguments

def hello_world(greeting: str = 'Hello'):
print(greeting + ' world!')

Note the spaces around the equal sign as opposed to how keyword arguments are usually styled.

Learn More

Must Read Python Interview Questions

200+ Python Tutorials With Coding Examples

Python Language Basics TutorialPython String Representations of Class Instances
Python For Beginners TutorialPython Debugging Tutorial
Python Data Types TutorialReading and Writing CSV File Using Python
Python Indentation TutorialWriting to CSV in Python from String/List
Python Comments and Documentation TutorialPython Dynamic Code Execution Tutorial
Python Date And Time TutorialPython Code Distributing using Pyinstaller
Python Date Formatting TutorialPython Data Visualization Tutorial
Python Enum TutorialPython Interpreter Tutorial
Python Set TutorialPython Args and Kwargs
Python Mathematical Operators TutorialPython Garbage Collection Tutorial
Python Bitwise Operators TutorialPython Pickle Data Serialisation
Python Bolean Operators TutorialPython Binary Data Tutorial
Python Operator Precedance TutorialPython Idioms Tutorial
Python Variable Scope And Binding TutorialPython Data Serialization Tutorial
Python Conditionals TutorialPython Multiprocessing Tutorial
Python Comparisons TutorialPython Multithreading Tutorial
Python Loops TutorialPython Processes and Threads
Python Arrays TutorialPython Concurrency Tutorial
Python Multidimensional Arrays TutorialPython Parallel Computation Tutorial
Python List TutorialPython Sockets Module Tutorial
Python List Comprehensions TutorialPython Websockets Tutorial
Python List Slicing TutorialSockets Encryption Decryption in Python
Python Grouby() TutorialPython Networking Tutorial
Python Linked Lists TutorialPython http Server Tutorial
Linked List Node TutorialPython Flask Tutorial
Python Filter TutorialIntroduction to Rabbitmq using Amqpstorm Python
Python Heapq TutorialPython Descriptor Tutorial
Python Tuple TutorialPython Tempflile Tutorial
Python Basic Input And Output TutorialInput Subset and Output External Data Files using Pandas in Python
Python Files And Folders I/O TutorialUnzipping Files in Python Tutorial
Python os.path TutorialWorking with Zip Archives in Python
Python Iterables And Iterators Tutorialgzip in Python Tutorial
Python Functions TutorialStack in Python Tutorial
Defining Functions With List Arguments In PythonWorking with Global Interpreter Lock (GIL)
Functional Programming In PythonPython Deployment Tutorial
Partial Functions In PythonPython Logging Tutorial
Decorators Function In PythonPython Server Sent Events Tutorial
Python Classes TutorialPython Web Server Gateway Interface (WSGI)
Python Metaclasses TutorialPython Alternatives to Switch Statement
Python String Formatting TutorialPython Packing and Unpacking Tutorial
Python String Methods TutorialAccessing Python Sourcecode and Bytecode
Using Loops Within Functions In PythonPython Mixins Tutorial
Python Importing Modules TutorialPython Attribute Access Tutorial
Difference Betweeb Module And Package In PythonPython Arcpy Tutorial
Python Math Module TutorialPython Abstract Base Class Tutorial
Python Complex Math TutorialPython Plugin and Extension Classes
Python Collections Module TutorialPython Immutable Datatypes Tutorial
Python Operator Module TutorialPython Incompatibilities Moving from Python 2 to Python 3
Python JSON Module TutorialPython 2to3 Tool Tutorial
Python Sqlite3 Module TutorialNon-Official Python implementations
Python os Module TutorialPython Abstract Syntax Tree
Python Locale Module TutorialPython Unicode and Bytes
Python Itertools Module TutorialPython Serial Communication (pyserial)
Python Asyncio Module TutorialNeo4j and Cypher using Py2Neo
Python Random Module TutorialBasic Curses with Python
Python Functools Module TutorialTemplates in Python
Python dis Module TutorialPython Pillow
Python Base64 Module TutorialPython CLI subcommands with precise help output
Python Queue Module TutorialPython Database Access
Python Deque Module TutorialConnecting Python to SQL Server
Python Webbrowser Module TutorialPython and Excel
Python tkinter TutorialPython Turtle Graphics
Python pyautogui Module TutorialPython Persistence
Python Indexing And Slicing TutorialPython Design Patterns
Python Plotting With Matplotlib TutorialPython hashlib
Python Graph Tool TutorialCreating a Windows Service Using Python
Python Generators TutorialMutable vs Immutable (and Hashable) in Python
Python Reduce TutorialPython configparser
Python Map Function TutorialPython Optical Character Recognition
Python Exponentiation TutorialPython Virtual Environments
Python Searching TutorialPython Virtual Environment – virtualenv
Sorting Minimum And Maximum In PythonPython Virtual environment with virtualenvwrapper
Python Print Function TutorialCreate virtual environment with virtualenvwrapper in windows
Python Regular Expressions Regex TutorialPython sys Tutorial
Copying Data In Python TutorialChemPy – Python package
Python Context Managers (“with” Statement) TutorialPython pygame
Python Name Special Variable TutorialPython pyglet
Checking Path Existence And Permissions In PythonWorking with Audio in Python
Creating Python Packages TutorialPython pyaudio
Usage of pip Module In Python TutorialPython shelve
Python PyPi Package Manager TutorialIoT Programming with Python and Raspberry PI
Parsing Command Line Arguments In Pythonkivy – Cross-platform Python Framework for NUI Development
Python Subprocess Library TutorialPandas Transform
Python setup.py TutorialPython vs. JavaScript
Python Recursion TutorialCall Python from C#
Python Type Hints TutorialPython Writing Extensions
Python Exceptions TutorialPython Lex-Yacc
Raise Custom Exceptions In PythonPython Unit Testing
Python Commonwealth Exceptions TutorialPython py.test
Python urllib TutorialPython Profiling
Web Scraping With Python TutorialPython Speed of Program
Python HTML Parsing TutorialPython Performance Optimization
Manipulating XML In PythonPython Security and Cryptography
Python Requests Post TutorialSecure Shell Connection in Python
Python Distribution TutorialPython Anti Patterns
Python Property Objects TutorialPython Common Pitfalls
Python Overloading TutorialPython Hidden Features
Python Polymorphism TutorialPython For Machine Learning
Python Method Overriding TutorialPython Interview Questions And Answers For Experienced
Python User Defined Methods TutorialPython Coding Interview Questions And Answers
Python Programming Tutorials With Examples

Other Python Tutorials

Leave a Comment