Can you define aliases for imported modules in Python?
Asked Answered
T

6

194

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

Trinitytrinket answered 1/4, 2009 at 17:33 Comment(0)
D
268
import a_ridiculously_long_module_name as short_name

also works for

import module.submodule.subsubmodule as short_name
Dimissory answered 1/4, 2009 at 17:34 Comment(2)
from module import sub_module_1 as s1, sub_module_2 as s2Wicklow
Can you do this for functions too? E.g. from normal_module import super_duper_ridiculously_long_function_name as supe?Beta
V
55

Check here

import module as name

or

from relative_module import identifier as name
Valine answered 1/4, 2009 at 17:34 Comment(2)
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?Landside
It seems you can't, here is the clearest answer I found for that stackoverflow.com/a/40823467Channing
U
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.

Unfinished answered 1/4, 2009 at 22:22 Comment(3)
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.xNonrigid
This is the technically correct response for the question: aliases for imported modules.Terrazzo
The reason this is possible is that modules are first-class objects in Python.Prohibitive
M
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
Misreport answered 17/10, 2018 at 17:7 Comment(0)
S
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).

Spongy answered 4/9, 2022 at 8:45 Comment(2)
NP in capitals for numpy??Heyday
Sorry, small lettersSpongy
P
-5

from MODULE import TAGNAME as ALIAS

Patience answered 11/5, 2020 at 15:6 Comment(2)
Can you please be more specific? This answer isn't formatted properly, and it doesn't give an explanation.Opening
The answer doesn't even provide something newBillion

© 2022 - 2024 — McMap. All rights reserved.