Python : 'import module' vs 'import module as'

会有一股神秘感。 提交于 2020-07-10 06:21:55

问题


Is there any differences among the following two statements?

import os
import os as os

If so, which one is more preferred?


回答1:


The below syntax will help you in understanding the usage of using "as" keyword while importing modules

 import NAMES as RENAME from MODULE searching HOW

Using this helps developer to make use of user specific name for imported modules. Example:

 import random 
 print random.randint(1,100)

Now I would like to introduce user specific module name for random module thus I can rewrite the above code as

 import random as myrand
 print myrand.randint(1,100)

Now coming to your question; Which one is preferred? The answer is your choice; There will be no performance impact on using "as" as part of importing modules.




回答2:


It is just used for simplification,like say

import random
print random.randint(1,100)

is same as:

import random as r
print r.randint(1,100)

So you can use r instead of random everytime.




回答3:


Is there any differences among the following two statements?

No.

If so, which one is more preferred?

The first one (import os), because the second one does the exact same thing but is longer and repeats itself for no reason.




回答4:


If you want to use name f for imported module foo, use

import foo as f
# other examples
import numpy as np
import pandas as pd

In your case, use import os




回答5:


The import .... as syntax was designed to limit errors.

This syntax allows us to give a name of our choice to the package or module we are importing—theoretically this could lead to name clashes, but in practice the as syntax is used to avoid them.

Renaming is particularly useful when experimenting with different implementations of a module.

Example: if we had two modules ModA and ModB that had the same API we could write import ModA as MyMod in a program, and later on switch to using import MoB as MyMod.

In answering your question, there is no preferred syntax. It is all up to you to decide.



来源:https://stackoverflow.com/questions/31469611/python-import-module-vs-import-module-as

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!