167

In Python, is it possible to define an alias for an imported module?

For instance:

import a_ridiculously_long_module_name

...so that is has an alias of 'short_name'.

CharlesB
  • 80,832
  • 27
  • 184
  • 208
Jordan Parmer
  • 34,480
  • 28
  • 95
  • 119

5 Answers5

232
import a_ridiculously_long_module_name as short_name

also works for

import module.submodule.subsubmodule as short_name
vartec
  • 125,354
  • 36
  • 211
  • 241
  • from module import sub_module_1 as s1, sub_module_2 as s2 – phreed Dec 19 '19 at 16:39
  • Can you do this for functions too? E.g. `from normal_module import super_duper_ridiculously_long_function_name as supe`? – Lou Feb 02 '21 at 14:38
45

Check here

import module as name

or

from relative_module import identifier as name
Brian R. Bondy
  • 327,498
  • 120
  • 583
  • 623
35

If you've done:

import long_module_name

you can also give it an alias by:

lmn = long_module_name

There's no reason to do it this way in code, but I sometimes find it useful in the interactive interpreter.

John Fouhy
  • 39,311
  • 19
  • 61
  • 77
  • 6
    For some purposes this is better than the top answers (import long_module_name as lmn) because you can still reference the module by both long_module_name.x and lmn.x – Anas Elghafari Aug 14 '14 at 14:27
  • This is the technically correct response for the question: aliases for imported modules. – DigitalEye Oct 22 '15 at 18:05
  • 2
    The reason this is possible is that modules are first-class objects in Python. – md2perpe Apr 10 '17 at 15:17
2

Yes, modules can be imported under an alias name. using as keyword. See

import math as ilovemaths # here math module is imported under an alias name
print(ilovemaths.sqrt(4))  # Using the sqrt() function
realmanusharma
  • 70
  • 1
  • 10
-4

from MODULE import TAGNAME as ALIAS

邢烽朔
  • 13
  • 2