189

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
  • 86,532
  • 28
  • 194
  • 218
Jordan Parmer
  • 36,042
  • 30
  • 97
  • 119

6 Answers6

260
import a_ridiculously_long_module_name as short_name

also works for

import module.submodule.subsubmodule as short_name
vartec
  • 131,205
  • 36
  • 218
  • 244
  • 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
53

Check here

import module as name

or

from relative_module import identifier as name
Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636
42

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
  • 41,203
  • 19
  • 62
  • 77
  • 7
    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
3

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
  • 330
  • 2
  • 10
0

Yes, you can define aliases for imported modules in Python.

Using pandas is considered a best practice in python because Pandas can import most file formats and link to databases.

Example: Import pandas library

import pandas as pd

Explaining:

pd: is the conventional alias for pandas.

NP: is the conventional alias for Numpy.

Using short alias helps keep code (concise) and (clean).

-5

from MODULE import TAGNAME as ALIAS

邢烽朔
  • 11
  • 2