[Python-Dev] import curdir,pardir,sep,pathsep,defpath from relevant *path module

Jeff Epler jepler@unpythonic.net
Fri, 14 Feb 2003 08:16:23 -0600


On Fri, Feb 14, 2003 at 11:13:25AM +0000, Michael Hudson wrote:
> I know Guido's squashed the idea, but how would you issue a warning on
> use of a module level global?

You could arrange to have a subclass of module that warns in
__getattribute__:

>>> os1 = reload(mwd).ModuleWithDeprecations('os', os, ['sep'])
<module '?' (built-in)> {}
>>> os1.path
<module 'posixpath' from '/usr/lib/python2.2/posixpath.pyc'>
>>> os1.sep
__main__:1: DeprecationWarning: os.sep is deprecated
'/'
>>> os1.__deprecated__
{'sep': '/'}
>>> 'sep' in dir(os1)
0

If ModuleWithDeprecations was coded in C, the performance impact (which
would only occur on AttributeErrors) would probably be small, and no
more than one test+branch for modules with nothing __deprecated__.


import types

import warnings

class ModuleWithDeprecations(types.ModuleType):

    def __init__(self, name, module, deprecated):
        types.ModuleType.__init__(self, name)
        print self, self.__dict__
        self.__dict__.update(module.__dict__)
        self.__deprecated__ = {}
        for item in deprecated:
            self.__deprecated__[item] = self.__dict__[item]
            del self.__dict__[item]

    def __getattribute__(self, attr):
        try:
            return types.ModuleType.__getattribute__(self, attr)
        except AttributeError:
            if attr in self.__deprecated__:
                warnings.warn("%s.%s is deprecated" % (self.__name__, attr),
                                DeprecationWarning, 2)
                return self.__deprecated__[attr]
            else:
                raise