decorator,它允许您在函数或方法中指定参数的有效类型。
RequireType的Python项目详细描述
什么
decorator,它允许您在 功能或方法。
如果调用与所需类型不匹配,则将失败 TypeError异常。
为什么?
在某些情况下(todo:添加一些示例),您希望/需要指定 要使用的特定类型,并且由于python没有参数的类型检查 这是有用的地方。
<> P>所有我发现的解决方案都有问题或者没有 我想要的功能,所以我自己做了。如何使用?
- 首先,安装RequireType包,可以使用pip:
- PIP安装要求类型
在代码中,您只需要导入并使用requiredecorator。
示例:
from requiretype import require @require(name=str, age=(int, float, long)) def greet_person(name, age): print "Hello {0} ({1})".format(name, age) >>> greet_person("John", 42) Hello John (42) >>> greet_person("John", "Doe") [...traceback...] TypeError: Doe is not a valid type. Valid types: <type 'int'>, <type 'float'>, <type 'long'> >>> greet_person(42, 43) [...traceback...] TypeError: 42 is not a <type 'str'> type
一些注释
这里有一些关于这个图书馆的细节。大多数是在一个或 帮助您强制/检查/要求类型和imo的更多包不是 很好的东西激励我写这篇文章。
要求类型:
- does not modify ^{tt5}$ or ^{tt6}$
- does not move arguments from one place to another
- support both ^{tt5}$ and ^{tt6}$
- allows you to use all the python 2.x supported parameters usage (if not, please report a bug)
- use named arguments type definition
- allows you to enforce a subset of all the available arguments
- raise a standard ^{tt1}$ if the arguments type are wrong