How do you alias a type in Python?

Lara picture Lara · Oct 9, 2015 · Viewed 11.8k times · Source

In some (mostly functional) languages you can do something like this:

type row = list(datum)

or

type row = [datum]

So that we can build things like this:

type row = [datum]
type table = [row]
type database = [table]

Is there a way to do this in Python? You could do it using classes, but Python has quite some functional aspects so I was wondering if it could be done an easier way.

Answer

Łukasz Rogalski picture Łukasz Rogalski · Oct 9, 2015

Since Python 3.5 you may use typing module.

Quoting docs, A type alias is defined by assigning the type to the alias:

Vector = List[float]

To learn more about enforcing types in Python you may want to get familiar with PEPs: PEP483 and PEP484.

Python historically was using duck-typing instead of strong typing and hadn't built-in way of enforcing types before 3.5 release.