在 Python 中断言变量类型的正确方法 [英] Proper way to assert type of variable in Python
问题描述
在使用函数时,我希望确保变量的类型符合预期.怎么做才对?
In using a function, I wish to ensure that the type of the variables are as expected. How to do it right?
下面是一个假函数的例子,它在继续其角色之前试图做到这一点:
Here is an example fake function trying to do just this before going on with its role:
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()
断言是正确的方法吗?我应该改用 try/except 吗?
Is assert the right approach? Should I use try/except instead?
此外,我的断言测试集似乎无法正常工作:S
Also, my assert set of tests does not seem to work properly :S
感谢 pythoneers
Thanks pythoneers
推荐答案
isinstance
如果你真的必须,内置是首选的方式,但更好的是记住 Python 的座右铭:请求宽恕比许可更容易"!-)(这实际上是 Grace Murray Hopper 的最爱座右铭;-).即:
The isinstance
built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:
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')
顺便说一句,这让函数可以在 Unicode 字符串上正常工作——无需任何额外的努力!-)
This, BTW, lets the function work just fine on Unicode strings -- without any extra effort!-)
这篇关于在 Python 中断言变量类型的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!