Python @precondition / @postcondition 用于成员函数 - 如何?

2024-01-01

我试图在类的成员函数返回的值上使用 @postcondition 装饰器,如下所示:

def out_gt0(retval, inval):
    assert retval > 0, "Return value < 0"

class foo(object):
    def __init__(self, w, h):
        self.width = w
        self.height = h
    @postcondition(out_gt0)
    def bar(self):
        return -1

当我尝试调用成员函数“bar”(并因此引发@postcondition提供警告)时,我得到以下信息:

>>> f = foo(2,3)
>>> f.bar()
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    f.bar()
  File "<pyshell#8>", line 106, in __call__
    result = self._func(*args, **kwargs)
TypeError: bar() takes exactly 1 argument (0 given)
>>> 

我对 @postcondition 的定义是这里看到的http://wiki.python.org/moin/PythonDecoratorLibrary#Pre-.2FPost-Conditions http://wiki.python.org/moin/PythonDecoratorLibrary#Pre-.2FPost-Conditions.

我假设出现错误是因为 @postcondition 底层的函数不希望处理成员函数(当然我见过的所有示例都只是使用普通的旧函数),但我不确定如何修复它,所以我可以这样做吗?

如有任何建议,将不胜感激。


你不需要做任何特别的事情:

import functools

def condition(pre_condition=None, post_condition=None):
    def decorator(func):
        @functools.wraps(func) # presever name, docstring, etc
        def wrapper(*args, **kwargs): #NOTE: no self
            if pre_condition is not None:
               assert pre_condition(*args, **kwargs)
            retval = func(*args, **kwargs) # call original function or method
            if post_condition is not None:
               assert post_condition(retval)
            return retval
        return wrapper
    return decorator

def pre_condition(check):
    return condition(pre_condition=check)

def post_condition(check):
    return condition(post_condition=check)

Usage:

@pre_condition(lambda arg: arg > 0)
def function(arg): # ordinary function
    pass

class C(object):
    @post_condition(lambda ret: ret > 0)
    def method_fail(self):
        return 0
    @post_condition(lambda ret: ret > 0)
    def method_success(self):
        return 1

Test:

function(1)
try: function(0)
except AssertionError: pass
else: assert 0, "never happens"

c = C()
c.method_success()
try: c.method_fail()
except AssertionError: pass
else: assert 0, "never happens"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python @precondition / @postcondition 用于成员函数 - 如何? 的相关文章

  • 导入错误:无法导入名称“FFProbe”

    我无法获取ffprobe包 https github com simonh10 ffprobe在 Python 3 6 中工作 我使用 pip 安装它 但是当我输入import ffprobe it says Traceback most
  • 在函数内的 for 循环上使用 tqdm 来检查进度

    我正在使用 for 循环迭代目录树内的一大组文件 这样做时 我想通过控制台中的进度条来监视进度 因此 我决定使用 tqdm 来实现此目的 目前 我的代码如下所示 for dirPath subdirList fileList in tqdm
  • 从 torch.autograd.gradcheck 导入 zero_gradients

    我想复制代码here https github com LTS4 DeepFool blob master Python deepfool py 并且我在 Google Colab 中运行时收到以下错误 ImportError 无法导入名称
  • 从所有数据帧列中删除子字符串

    我有一个单词列表 大约 1000 个单词 我称之为负面单词 CAST ARTICLES SANITARY JAN CLAUSES SPECIAL ENDORSEMENT 我很快就会用这个单词列表制作一个数据框 我还有一个数据框 看起来像 F
  • 如何替换Python字符串中的正确字母

    任务是 您的任务是纠正数字化文本中的错误 您只需处理以下错误 S 被误解为 5 O 被误解为 0 I 被误解为 1 我的代码 def correct string for i in string if 5 in string string
  • 使用 Pandas 从 csv 文件读取标题信息

    我有一个包含 14 行标题的数据文件 在标头中 有经纬度坐标和时间的元数据 我目前正在使用 pandas read csv filename delimiter header 14 读取文件 但这只是获取数据 我似乎无法获取元数据 有人知道
  • 如何用函数记录一个文件?

    我有一个带有函数 lib py 但没有类的python 文件 每个函数都有以下样式 def fnc1 a b c This fonction does something param a lalala type a str param b
  • NSUserNotificationCenter.defaultUserNotificationCenter() 使用 PyInstaller 返回 None

    我正在尝试将通知发送到通知中心 Mac OSX 我正在使用 PyObjC 绑定来使用我们的 python 应用程序中的 cocoa api 我正在使用以下代码片段 import Foundation import objc NSUserNo
  • 使用 scikit 时 scipy.sparse 矩阵的缩放问题

    在使用 scikit learn 解决机器学习问题时 我需要在使用 SVM 进行训练之前对 scipy sparse 矩阵进行缩放 但在文档 http scikit learn org stable modules preprocessin
  • 在 Python 中从 Excel 复制 YEARFRAC() 函数

    因此 我使用 python 来自动执行一些必须在 Excel 中执行的重复任务 我需要做的计算之一需要使用yearfrac 这在Python中被复制了吗 I found this https lists oasis open org arc
  • Python在没有pandas的情况下解码excel表

    我正在尝试在 python 中读取 excel 文件而不使用pandas or xlrd 我一直在尝试将结果转换为bytes to utf 8没有任何成功 xls 文件中的数据 colA colB colC spc 1D0 20190705
  • pandas groupby 操作缺少数据

    在 pandas 数据框中 我有一列如下所示 0 M 1 E 2 L 3 M 1 4 M 2 5 M 3 6 E 1 7 E 2 8 E 3 9 E 4 10 L 1 11 L 2 12 M 1 a 13 M 1 b 14 M 1 c 15
  • 将图与热图(可能是对数)配对?

    How to create a pair plot in Python like the following but with heat maps instead of points or instead of a hex bin plot
  • 如何从邻接表高效创建稀疏邻接矩阵?

    我正在与last fm http labrosa ee columbia edu millionsong lastfm数据集来自百万歌曲数据集 http labrosa ee columbia edu millionsong 数据以一组 j
  • 在Python中使用pil读取tif图像时出现值错误?

    我必须读取尺寸的tif图像2200 2200并输入 uint16 我将 PIL 库与 anaconda python 一起使用 如下所示 from PIL import Image img Image open test tif img i
  • 如何创建增量加载网页

    我正在编写一个处理大量数据的页面 它会永远持续到我的结果页面加载 几乎无限 因为返回的数据太大了 因此 我需要实现一个增量加载页面 例如 url 中的页面 http docs python org http docs python org
  • 如何在引发异常时将变量传递给异常并在异常时检索它?

    现在我只有一个空白的异常类 我想知道如何在引发变量时给它一个变量 然后在 try except 中处理它时检索该变量 class ExampleException Exception pass 为其构造函数提供一个参数 将其存储为属性 然后
  • 类返回语句不打印任何输出

    我正在学习课程 但遇到了问题return语句 它是语句吗 我希望如此 程序什么也没有打印出来 它只是结束而不做任何事情 class className def createName self name self name name def
  • 纠正装饰器模式的一个大缺点

    不久前 我在重构一些游戏战斗代码时决定尝试装饰器模式 战斗者可以拥有各种被动能力 也可能是不同类型的生物 我认为装饰器可以让我在运行时以各种组合添加行为 因此我不需要数百个子类 我几乎已经完成了 15 个左右的被动能力装饰器 在测试中我发现
  • 从 Django 运行 shell 命令

    我正在 Django 中开发一个网页 使用 apache 服务器 需要调用 shell 命令来启用 禁用一些守护进程 我尝试这样做 os system service httpd restart 1 gt HOME out 2 gt HOM

随机推荐