Python Forum

Full Version: making a module mimic another module
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i want to create a module that mimics another module in a special way. in order to do this i need to create functions in my module with names discovered when that other module is imported. the names to be created are different than what the imported module has. the big problem is that locals() is not supposed to be used to add names to the local name space. is there any alternative way to do that? or is globals() the more appropriate way (in my module at the time it gets imported) to add variables dynamically (by name figured out at import time).
You can create a new module by using the constructor types.ModuleType()
>>> import os
>>> import types
>>> m = types.ModuleType('OS')
>>> for k in dir(os):
...     setattr(m, k.upper(), getattr(os, k))
... 
>>> m.CHDIR
<built-in function chdir>
>>> import sys
>>> sys.modules[m.__name__] = m # optional, if you want to make it importable
>>> import OS
>>> OS is m
True