199

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

6 Answers 6

276
import a_ridiculously_long_module_name as short_name

also works for

import module.submodule.subsubmodule as short_name
Sign up to request clarification or add additional context in comments.

2 Comments

from module import sub_module_1 as s1, sub_module_2 as s2
Can you do this for functions too? E.g. from normal_module import super_duper_ridiculously_long_function_name as supe?
59

Check here

import module as name

or

from relative_module import identifier as name

2 Comments

Hmm, when I try to do from name import X (after the alias definition) I get No module named name. Can we import modules from aliases?
It seems you can't, here is the clearest answer I found for that stackoverflow.com/a/40823467
41

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.

4 Comments

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
This is the technically correct response for the question: aliases for imported modules.
The reason this is possible is that modules are first-class objects in Python.
For unknown reason you package aliasing does not work. Later I can not import subpackages by that name with "from" and "dot" (from lmn.some_sub_name import york).
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

Comments

-1

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

2 Comments

NP in capitals for numpy??
Sorry, small letters
-5

from MODULE import TAGNAME as ALIAS

2 Comments

Can you please be more specific? This answer isn't formatted properly, and it doesn't give an explanation.
The answer doesn't even provide something new

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.