Mor*_*ock 57 python testing assert
在使用函数时,我希望确保变量的类型符合预期.怎么做对了?
这是一个假冒函数的示例,在继续其角色之前尝试执行此操作:
def my_print(begin, text, end):
"""Print 'text' in UPPER between 'begin' and 'end' in lower
"""
for i in (begin, text, end):
assert isinstance(i, str), "Input variables should be strings"
out = begin.lower() + text.upper() + end.lower()
print out
def test():
"""Put your test cases here!
"""
assert my_print("asdf", "fssfpoie", "fsodf")
assert not my_print("fasdf", 33, "adfas")
print "All tests passed"
test()
Run Code Online (Sandbox Code Playgroud)
断言是正确的方法吗?我应该使用try/except吗?
此外,我的断言测试集似乎不能正常工作:S
谢谢pythoneers
Ale*_*lli 52
在isinstance内置的是,如果你真的必须的首选方式,但更重要的是要记住Python的座右铭:"它更容易请求原谅比许可" - )(它实际上是格雷斯穆雷Hopper的喜欢的格言;-)!即:
def my_print(text, begin, end):
"Print 'text' in UPPER between 'begin' and 'end' in lower"
try:
print begin.lower() + text.upper() + end.lower()
except (AttributeError, TypeError):
raise AssertionError('Input variables should be strings')
Run Code Online (Sandbox Code Playgroud)
这个,BTW,让函数在Unicode字符串上运行得很好 - 无需任何额外的努力! - )
Noc*_*wer 12
您可能想要在2.6版本的Python中尝试此示例.
def my_print(text, begin, end):
"Print text in UPPER between 'begin' and 'end' in lower."
for obj in (text, begin, end):
assert isinstance(obj, str), 'Argument of wrong type!'
print begin.lower() + begin.upper() + end.lower()
Run Code Online (Sandbox Code Playgroud)
但是,您是否考虑过让这个功能自然失败?
Tim*_*mmm 12
isinstance(x, str) is best if you can use it, but it does not work with generics. For example you cannot do:
isinstance(x, dict[str, int])
Run Code Online (Sandbox Code Playgroud)
It will give a runtime error:
TypeError: isinstance() argument 2 cannot be a parameterized generic
Run Code Online (Sandbox Code Playgroud)
If you are only interested in asserting a type for a static type checker you can use cast:
TypeError: isinstance() argument 2 cannot be a parameterized generic
Run Code Online (Sandbox Code Playgroud)
Unlike isinstance() it doesn't actually do the type check so you have to check all of the keys and values yourself if necessary.
(我意识到这并不完全是您所要求的,但“类型断言”也用于指代类似的事物cast(),因此我避免了另一个会因重复而关闭的问题。)
做type('')有效地等同于str和types.StringType
所以type('') == str == types.StringType会评价为" True"
请注意,如果以这种方式检查类型,只包含ASCII的Unicode字符串将失败,因此您可能希望执行类似assert type(s) in (str, unicode)或assert isinstance(obj, basestring)后者的操作,后者在007Brendan的注释中建议并且可能是首选.
isinstance() 如果你想询问一个对象是否是一个类的实例,例如:
class MyClass: pass
print isinstance(MyClass(), MyClass) # -> True
print isinstance(MyClass, MyClass()) # -> TypeError exception
Run Code Online (Sandbox Code Playgroud)
但对于基本类型,例如str,unicode,int,float,long等询问,type(var) == TYPE将工作确定.
| 归档时间: |
|
| 查看次数: |
87045 次 |
| 最近记录: |