Python断言风格 [英] Python assertion style
问题描述
我想知道我在做什么是一种适当的断言方法.我正在尝试为 Python 的样式指南制作一些既简洁又非常正确的东西.
I'm wondering if what I'm doing is an appropriate method of assertions. I'm trying to making something both concise and very correct for Python's style guides.
try:
assert self.port_number == 0
assert self.handle == None
assert isinstance(port_number, int) or isinstance(port_number, float)
assert port_number > 0
except AssertionError:
return -1
*body of code*
return 0
以上是我的代码摘录,展示了我如何处理参数断言.您可以假设我已经涵盖了所有必要的断言,并且输入是 port_number.这被认为是好的风格吗?有没有更好的办法?
Above is an excerpt of my code that shows how I handle argument assertions. You can assume that I've covered all of the necessary assertions and the input is port_number. Is this considered good style? Is there a better way?
推荐答案
如果调用函数期望成功时输入 0,失败时输入 -1,我会这样写:
If the calling function expects input of 0 on success and -1 on failure, I would write:
def prepare_for_connection(*args, **kwargs):
if (self.handle is not None):
return -1
if not (isinstance(port_number, int) or isinstance(port_number, float)):
return -1
if port_number < 0:
return -1
# function body
return 0
为非异常行为调用抛出和捕获断言错误的机制开销太大.断言更适用于语句应该始终为真的情况,但如果不是由于某些错误,您会在该位置大声地生成错误,或者最好在该位置处理它(使用默认值).如果您愿意,您可以将多个 if 条件组合成一个巨大的条件语句;我个人认为这更具可读性.此外,python 风格是使用 is
和 is not
而不是 ==
和 与
.None
进行比较>!=
Invoking the mechanism of throwing and catching assertion errors for non-exceptional behavior is too much overhead. Assertions are better for cases where the statement should always be true, but if it isn't due to some bug you generate an error loudly in that spot or at best handle it (with a default value) in that spot. You could combine the multiple-if conditionals into one giant conditional statement if you prefer; personally I see this as more readable. Also, the python style is to compare to None
using is
and is not
rather than ==
and !=
.
一旦程序离开调试阶段,Python 应该能够优化掉断言.请参阅 http://wiki.python.org/moin/UsingAssertionsEffectively
Python should be able to optimize away assertions once the program leaves the debugging phase. See http://wiki.python.org/moin/UsingAssertionsEffectively
承认这种从函数返回错误号 (-1/0) 的 C 风格约定并不是特别 Pythonic.我会将 -1
替换为 False
并将 0
替换为 True
并给它一个语义上有意义的名称;例如,将其称为 connection_prepared = prepare_for_connection(*args,**kwargs)
,因此 connection_prepared
将是 True
或 False
并且代码将非常易读.
Granted this C-style convention of returning a error number (-1 / 0) from a function isn't particularly pythonic. I would replace -1
with False
and 0
with True
and give it a semantically meaningful name; e.g., call it connection_prepared = prepare_for_connection(*args,**kwargs)
, so connection_prepared
would be True
or False
and the code would be very readable.
connection_prepared = prepare_for_connection(*args,**kwargs)
if connection_prepared:
do_something()
else:
do_something_else()
这篇关于Python断言风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!