Python-2.7 executes code on object import

2.7 executes code on object import… here is a solution to the problem.

2.7 executes code on object import

I’m trying to make a deprecation system that allows code to run transparently to normal users, but marks deprecated objects in developer mode.

One issue I’m having is that I can import deprecated objects into another module even though I’m in developer mode. This means I’m missing places to use deprecated objects.

For example, in module1.py:

class MyObject(object):
    pass
MyObject = MyObject if not dev_mode() else DeprecatedObject

Then in the module2.py:

from module1 import MyObject

I’ve set up DeprecatedObject so any interaction with it raises a DeprecationWarning – is there any way to get it wrong on import? IE。 Even importing module2.py throws an exception.

I was imagining something like this :

import warnings

class DeprecatedObject(object):
    ...
    def __onimport__(self):
        warnings.warn("deprecated", DeprecationWarning)

Solution

The module-level

__getattr__ feature allows module-level names to undergo the proper deprecation process at import time. This feature will appear in Python 3.7, see PEP 562 for more information (since you are already tagged with Python 2.7, it cannot help you, But I mention it for the benefit of future readers).

On Python 2.7, you have two poor options:

    A

  • deprecation warning is triggered in object __init__.
  • Use Guido’s hack to replace the module with its own patch version after import. Wrapping proxy objects around modules allows you to control name resolution.

Related Problems and Solutions