Python Forum
making a module mimic another module - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: making a module mimic another module (/thread-22616.html)



making a module mimic another module - Skaperen - Nov-20-2019

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).


RE: making a module mimic another module - Gribouillis - Nov-20-2019

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