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.
Python is dynamically typed. While Łukasz R.'s answer is correct for type hinting purposes (which can in turn be used for static analysis and linting), strictly speaking, you do not need to do anything to make this work. Just construct your lists like this and assign them to variables:
foo_table = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
bar_table = ...
foo_database = [foo_table, bar_table, ...]
Type hints are genuinely useful, because they can help document how your code behaves, and they can be checked both statically and at runtime. But there's nothing forcing you to do so if it is inconvenient.
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.
How about something like row = lambda datum: list(datum)
? No real type introspection support there, but it's a very simple way of "aliasing" types given Python's fondness for duck typing. And it's functional! Kinda.
来源:https://stackoverflow.com/questions/33045222/how-do-you-alias-a-type