如何保存或识别调用者的堆栈帧?

2024-04-19 01:50:31 发布

您现在位置:Python中文网/ 问答频道 /正文

今天我的大脑感觉很慢。在

我用Python中的decorator编写pre/post/invariant。目前,我需要每个调用来指定上下文的局部变量和全局变量,这感觉很难看。是否有一种方法可以从decorator应用程序级别获取局部变量和全局变量,即使它的深度是任意的。在

也就是说,我正试图编写一个难看的代码: 从dectools导入不变量,前,后,调用

@invariant("self.price >= 0 and self.inventory >= 0 and Item.tax_rate >= 0")
class Item(object):
    tax_rate = 0.10  # California.  No property taxes on old property.

    @post("ItemDB.fetch(self) = (name, price)", locals(), globals())
    def __init__(self, name, price):
        self.name = name
        self.price = price
        self.total_sold = 0
        self.inventory = 0

    @call_if(check_level, "manager")
    @post("self.total_sold > 0", locals(), globals())
    @pre("discount > 0 and discount <= self.price * 0.50", locals(), globals())
    def adjust_price(self, adjustment):
         ....

在没有所有“locals(),globals()”的情况下转换成同样丑陋的代码。我遇到了嵌套装饰器给我任意堆栈深度的问题,所以我的dectools.pre版无法从固定深度sys.\u getframe()中获取。这堆东西我玩得不多,如果有人耍花招,我会很感激的。(是的,我通过假设self在正确的堆栈框架中,将局部变量嵌入到局部变量中。它是项目税率这总是超出范围,以及self和ItemDB。)

提前谢谢你

查尔斯


Tags: and代码nameselfdecoratorpostpreprice
1条回答
网友
1楼 · 发布于 2024-04-19 01:50:31

如果您可以访问self.total_sold,那么您就可以访问self.tax_rate(这与Item.tax_rate是一样的,除非您踩踏它,这样就不会踩踏它,将税率保持为原始类变量,并通过self.访问它!-). 这将比在堆栈中捣乱要可靠得多,尤其是图片中的嵌套装饰器,这或多或少保证了脆弱的、特定于版本的代码(堆栈自省是为了调试目的而使用的,本质上,而不是。在

相关问题 更多 >