gpt4 book ai didi

python - 如何防止函数被转换为 bool

转载 作者:行者123 更新时间:2023-11-28 19:33:59 24 4
gpt4 key购买 nike

以下python代码有一个错误:

class Location(object):
def is_nighttime():
return ...

if location.is_nighttime:
close_shades()

错误是程序员忘记调用is_nighttime(或者忘记在方法上使用@property装饰器),所以方法被 cast by bool 在未被调用的情况下评估为 True

有没有办法阻止程序员这样做,无论是在上述情况下,还是在 is_nighttime 是独立函数而不是方法的情况下?例如,具有以下精神的东西?

is_nighttime.__bool__ = TypeError

最佳答案

理论上,您可以将函数包装在一个类似函数的对象中,其中包含委托(delegate)给函数的 __call__ 和引发 TypeError 的 __bool__。它真的很笨重,并且可能会导致比它捕获的更多的不良交互 - 例如,除非您为此添加更多特殊处理,否则这些对象将无法用作方法 - 但您可以这样做:

class NonBooleanFunction(object):
"""A function wrapper that prevents a function from being interpreted as a boolean."""
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def __bool__(self):
raise TypeError
__nonzero__ = __bool__

@NonBooleanFunction
def is_nighttime():
return True # We're at the Sun-Earth L2 point or something.

if is_nighttime:
# TypeError!

还有很多东西你抓不到:

nighttime_list.append(is_nighttime)  # No TypeError ._.

并且您必须记住将此显式应用于您不希望被视为 bool 值的任何函数。对于不受控制的函数和方法,您也无能为力;例如,您不能将此应用到 str.islower 以捕获类似 if some_string.islower: 的内容。

如果你想捕捉这样的东西,我建议改用静态分析工具。我认为像 PyCharm 这样的 IDE 可能会警告您,并且应该有可以捕捉到这一点的 linting 工具。


如果你想让这些东西作为方法工作,这里是额外的处理:

import functools

class NonBooleanFunction(object):
... # other methods omitted for brevity
def __get__(self, instance, owner):
if instance is None:
return self
return NonBooleanFunction(functools.partial(self.func, instance))

关于python - 如何防止函数被转换为 bool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37335027/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com