Importing individual elements with a namespace

I want to import certain elements from a module - only those that are needed, not all elements of that module, but want to keep the namespace of the modules i.e. save the module name as a "prefix" to access these elements. In other words, it is best to use the import module

and constructors from module import item

.

Is there a simpler / better construct to do this instead of doing the following (which is a lot of code, looks a bit awkward and still leaves unnecessary characters in the global namespace)?

from types import ModuleType
from myModule import Item1, Item2

myModule = ModuleType("myModule")
myModule.Item1 = Item1
myModule.Item2 = Item2

      

+3


source to share


1 answer


Yes, you can use:



from types import ModuleType as MT
from myModule import Item1 as It1, Item2 as It2

myModule = MT("myModule")
It1 = Item1
It2 = Item2

      

0


source







All Articles