You can adapt this ActiveState recipe , perhaps something like this:
# safemodule.py import sys import types import warnings class EncapsulationWarning(RuntimeWarning): pass class ModuleWrapper(types.ModuleType): def __init__(self, context): self.context = context super(ModuleWrapper, self).__init__( context.__name__, context.__doc__) def __getattribute__(self, key): context = object.__getattribute__(self, 'context') if hasattr(context, '__all__') and key not in context.__all__: warnings.warn('%s not in %s.__all__' % (key, context.__name__), EncapsulationWarning, 2) return context.__getattribute__(key) if 'old_import' not in globals(): old_import = __import__ def safe_import(*args, **kwargs): m = old_import(*args, **kwargs) return ModuleWrapper(m) __builtins__['__import__'] = safe_import
Then use it as follows:
C:\temp>python ActivePython 2.5.2.2 (ActiveState Software Inc.) based on Python 2.5.2 (r252:60911, Mar 27 2008, 17:57:18) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import safemodule >>> import sys >>> type(sys) <class 'safemodule.ModuleWrapper'> >>>
You can, of course, adapt this to wrap only some modules, etc.
Vinay sajip
source share