Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How can you use a module's alias to import its submodules?

Tags:

python

module

I have a long module name and I want to avoid having to type it all over many times in my document. I can simply do import long_ass_module_name as lamn and call it that way. However, this module has many submodules that I wish to import and use as well.

In this case I won't be able to write import lamn.sub_module_1 because python import does not recognize this alias I made for my long_ass_module_name. How can I achieve this?

Should I simply automatically import all submodules in my main module's __init__.py?

like image 930
levesque Avatar asked Feb 03 '12 17:02

levesque


2 Answers

An aliased object still changes when you import submodules,

import my_long_module_name as mlmn
import my_long_module_name.submodule

mlmn.submodule.function()

The import statement always takes the full name of the module. The module is just an object, and importing a submodule will add an attribute to that object.

like image 77
Dietrich Epp Avatar answered Oct 31 '22 16:10

Dietrich Epp


This (highly unrecommendable) way of importing all the members of an object to the current namespace works by looking up the vars() dictionary:

import my_bad_ass_long_module.bafd as b

# get __dict__ of current namespace
myn = vars() 
for k,v in vars(b).items():
  # populate this namespace with the all the members of the b namespace (overwriting!)
  myn[k] = v
like image 1
gauteh Avatar answered Oct 31 '22 15:10

gauteh