How to mark a global as deprecated in Python?
Question: [I've seen
decorators](http://wiki.python.org/moin/PythonDecoratorLibrary#Smartdeprecationwarnings.28withvalidfilenames.2Clinenumbers.2Cetc..29)
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)
    

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.

Any ideas? Has anyone else tackled this problem?


Answer: 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.

