How do you alias a type?

自闭症网瘾萝莉.ら 提交于 2019-11-30 19:07:26

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!