A library with a set of tools for annotating types in Python code.
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.
annotation Added complex type support Sep 1, 2014
tests Added complex type support Sep 1, 2014
.gitignore Packaging using distutils Aug 19, 2014
COPYING Added copying Mar 5, 2013
README.rst Added complex type support Sep 1, 2014
setup.py Updated version Nov 17, 2014


Type annotations for Python



The typeannotations module provides a set of tools for type checking and type inference of Python code. It also a provides a set of types useful for annotating functions and objects.

These tools are mainly designed to be used by static analyzers such as linters, code completion libraries and IDEs. Additionally, decorators for making run-time checks are provided. Run-time type checking is not always a good idea in Python, but in some cases it can be very useful.

Run-time type checking.

The typechecked decorator can be used to check types specified in function annotations. For example:

>>> @typechecked
... def test(a: int) -> int:
...     return a
>>> test(1)
>>> test('string')
Traceback (most recent call last):
TypeError: Incorrect type for "a"

Structural interfaces

The Interface class allows you to define interfaces that are checked dynamically. You don't have to explicitly indicate when an object or class implements a given Interface. If an object provides the methods and attributes specified in the Interface, it's considered a valid implementation.

For example, let's define a simple interface:

>>> class Person(Interface):
...     name = str
...     age = int
...     def say_hello(name: str) -> str:
...             pass

Any object defining those the name, age and say_hello() members is a valid implementation of that interface. For example:

>>> class Developer:
...     def __init__(self, name, age):
...             self.name = name
...             self.age = age
...     def say_hello(self, name: str) -> str:
...             return 'hello ' + name
>>> isinstance(Developer('bill', 20), Person)

This also works with built-in types:

>>> class IterableWithLen(Interface):
...     def __iter__():
...             pass
...     def __len__():
...             pass
>>> isinstance([], IterableWithLen)
>>> isinstance({}, IterableWithLen)
>>> isinstance(1, IterableWithLen)


A typedef is similar to an Interface except that it defines a single function signature. This is useful for defining callbacks. For example:

>>> @typedef
... def callback(event: Event) -> bool:
...     pass

Then it's possible to check if a function implements the same signature:

>>> def handler(event: MouseEvent) -> bool:
...     print('click')
...     return True
>>> isinstance(handler, callback)
>>> isinstance(lambda: True, callback)

Note that MouseEvent is a subclass of Event.

Type unions

A union is a collection of types and it's a type itself. An object is an instance of a union if it's an instance of any of the elements in the union. For example:

>>> NumberOrString = union(int, str)
>>> isinstance(1, NumberOrString)
>>> isinstance('string', NumberOrString)
>>> issubclass(int, NumberOrString)
>>> issubclass(str, NumberOrString)


A predicate is a special type defined by a function that takes an object and returns True or False indicating if the object implements the type. For example:

>>> Positive = predicate(lambda x: x > 0)
>>> isinstance(1, Positive)
>>> isinstance(0, Positive)

Predicates can also be defined using a decorator:

>>> @predicate
... def Even(object):
...     return object % 2 == 0

Predicates can also be combined using the &` operator:

>>> EvenAndPositive = Even & Positive

Predicates are useful for defining contracts:

>>> Positive = predicate(lambda x: x > 0)
>>> @typechecked
... def sqrt(n: Positive):
...     ...
>>> sqrt(-1)
Traceback (most recent call last):
TypeError: Incorrect type for "n"

The optional predicate

The optional predicate indicates that the object must be from the given type or None. For example:

>>> isinstance(1, optional(int))
>>> isinstance(None, optional(int))

And checking types at runtime:

>>> @typechecked
... def greet(name: optional(str) = None):
...     if name is None:
...             print('hello stranger')
...     else:
...             print('hello {0}'.format(name))
>>> greet()
hello stranger
>>> greet('bill')
hello bill

The only predicate

The only predicate indicates that an object can only be of the specified type, and not of any of its super classes. For example:

>>> isinstance(True, only(bool))
>>> isinstance(1, only(bool))

Note that in Python bool is a sublcass of int.

The options predicate

The options predicate indicates that the value of an object must be one of the given options. For example:

>>> FileMode = options('r', 'w', 'a', 'r+', 'w+', 'a+')
>>> isinstance('w', FileMode)
>>> isinstance('x', FileMode)

This is useful when defining a function:

>>> @typecheck
... def open(filename: str, mode: options('w', 'a')):
...          ...

Complex Types:

Complex types are also accepted in both interfaces and type specifications.

>>> @typechecked
... def test(a: { int: ( str, bool ) }) -> (bool, int):
...     return isinstance(a, dict), len(a)
>>> test({ 1: ('a', False) })
(True, 1)
>>> test('string')
Traceback (most recent call last):
TypeError: Incorrect type for "a"

The rules are:

  1. A list of types. The value must be a list containing only the specified types.
  2. A set of types. The value must be a set containing only the specified types.
  3. A tuple of types. The value must be a tuple containing the specified types in the specified order.
  4. A dict of types. The value must be a dict where each (key, value) pair is assocated with a (key, value) pair in the type dictionary.

Any of the complex types can nest and contain any other type.

To be implemented:

Function overloading

def isinstance(object, t: type):

def isinstance(object, t: tuple):

Annotate existing functions and libraries

def open_annotated(file: str,
                   mode: options('r', 'w', 'a', 'r+', 'w+', 'a+'),
                   buffering: optional(int)) -> IOBase:


Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
either express or implied. See the License for the specific language
governing permissions and limitations under the License.