如何在Python中将全局标记为已弃用? [英] How to mark a global as deprecated in Python?

查看:316
本文介绍了如何在Python中将全局标记为已弃用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过装饰器您将某个功能标记为已弃用,以便在使用该功能时发出警告。除了全局变量,我想做同样的事情,但是我想不出一种检测全局变量访问的方法。我知道globals()函数,可以检查它的内容,但这只会告诉我是否定义了global(如果不赞成使用该函数,而没有全部删除,则仍然会存在),而不是实际上是否在使用它。我能想到的最好的替代方法是这样的:

I've seen decorators that let you mark a function a deprecated so that a warning is given whenever that function is used. I'd like to do the same thing but for a global variable, but I can't think of a way to detect global variable accesses. I know about the globals() function, and I could check its contents, but that would just tell me if the global is defined (which it still will be if the function is deprecated and not all out removed) not if it's actually being used. The best alternative I can think of is something like this:

# myglobal = 3
myglobal = DEPRECATED(3)

但是,除了如何让已弃用的行为完全像 3的问题之外,不知道DEPRECATED可以执行的操作将使您在每次访问它时都进行检测。我认为最好的方法是遍历所有全局方法(因为Python中的所有内容都是对象,所以即使'3'也具有用于转换为字符串之类的方法),然后将它们装饰为不推荐使用。但这并不理想。

But besides the problem of how to get DEPRECATED to act exactly like a '3', I'm not sure what DEPRECATED could do that would let you detect every time it's accessed. I think the best it could do is iterate through all of the global's methods (since everything in Python is an object, so even '3' has methods, for converting to string and the like) and 'decorate' them to all be deprecated. But that's not ideal.

有什么想法吗?

推荐答案

您无法直接执行此操作,因为无法拦截模块访问。但是,您可以使用自己选择的对象作为代理来替换该模块,以查找对某些属性的访问:

You can't do this directly, since theres no way of intercepting the module access. However, you can replace that module with an object of your choosing that acts as a proxy, looking for accesses to certain properties:

import sys, warnings

def WrapMod(mod, deprecated):
    """Return a wrapped object that warns about deprecated accesses"""
    deprecated = set(deprecated)
    class Wrapper(object):
        def __getattr__(self, attr):
            if attr in deprecated:
                warnings.warn("Property %s is deprecated" % attr)

            return getattr(mod, attr)

        def __setattr__(self, attr, value):
            if attr in deprecated:
                warnings.warn("Property %s is deprecated" % attr)
            return setattr(mod, attr, value)
    return Wrapper()

oldVal = 6*9
newVal = 42

sys.modules[__name__] = WrapMod(sys.modules[__name__], 
                         deprecated = ['oldVal'])

现在,您可以将其用作:

Now, you can use it as:

>>> import mod1
>>> mod1.newVal
42
>>> mod1.oldVal
mod1.py:11: UserWarning: Property oldVal is deprecated
  warnings.warn("Property %s is deprecated" % attr)
54

缺点是,当您访问模块时,您现在正在执行两次查找,因此对性能会有轻微的影响。

The downside is that you are now performing two lookups when you access the module, so there is a slight performance hit.

这篇关于如何在Python中将全局标记为已弃用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆