简体   繁体   中英

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

Is there any differences among the following two statements?

import os
import os as os

If so, which one is more preferred?

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.

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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM