Python : 'import module' vs 'import module as' - python

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.

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.

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.

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.

Related

import statement in python

Why give full path to call a function when import statement is used to import a module from subpackage of package?
eg . A is package , AA is sub package of A , AA1 is module in AA
import A.AA.AA1
A.AA.AA1.AA1fun()
works correctly
but
AA1.AA1fun()
Why not this and why is 'A' got placed in global namespace why not 'AA1'?
Let's suppose that we perform an import of these two modules:
import A.AA.AA1
import B.AA.AA1
Which of the two modules would be chosen if you run the following functions?
AA.AA1.fun()
AA.AA1.fun()
AA1.fun()
AA1.fun()
To avoid this ambiguity you have to explicitly put the whole package, subpackage and module path.
A.AA.AA1.fun()
B.AA.AA1.fun()
If you want to avoid having to use the whole path every time, you have the from option:
from A.AA.AA1 import fun
fun()
But, by doing this, the name of the identifier fun is exposed. Therefore, if fun was already assigned to another object previously, it is overridden and now points to the new object in A.AA.AA1.
fun = lambda x: 2*x
from A.AA.AA1 import fun
from B.AA.AA1 import fun
In this last example, after executing these lines of code, fun refers only to the object in module B.AA.AA1.
You can also use the as option to create an alias to the imported module:
import A.AA.AA1 as AAA1
import B.AA.AA1 as BAA1
AAA1.fun()
BAA1.fun()
This way the whole path is abbreviated and avoids ambiguity when executing fun from one module or another.
In this link you can find the documentation: import doc
The main difference is in how import works, please refer to the docs section 5.4.2 for more information. As an example:
import A.AA.AA1
A.AA.AA1.AA1fun()
With as sole import you will have to provide the complete path. On the other hand, if you use a from statement you can use it directly:
from A.AA import AA1
AA1.AA1fun()

What is the PEP8 recommendation for multiple imports from a package?

The PEP8 style guide section on imports seems to be a bit ambiguous.
From: https://www.python.org/dev/peps/pep-0008/#imports
The first part makes sense:
# Imports should usually be on separate lines:
# Correct:
import os
import sys
# Wrong:
import sys, os
But then it goes on to say:
# It's okay to say this though:
# Correct:
from subprocess import Popen, PIPE
How should we interpret this? subprocess is a module, so is PEP8 saying it's just OK to import multiple things from a single module on one line? Or is it saying it's OK to import any number of things from a higher level entity on one line? I.e. is importing multiple modules from a package good style?
I'm sure arguments could be made for either style, so I'm not asking for opinions on that, but is there an authoritative source on what the PEP8 intent is here?

How can I use import, from import and sys.append together in Python

I have a directory I add to sys.path to import custom modules. What is the correct/best way to use import, from import and sys.path together? What I mean is if it acceptable to use sys.path.append in between the "imports".
For example:
#!C:/Python27
import sys
sys.path.append('C:\\Users\\user\\myPythonModules')
import writedata as wd
import os
import csv
from collections import defaultdict
Edit:
I should have mentioned that writedata would be a custom module that I want to import as wd. The module writedata is located in C:\\Users\\user\\myPythonModules
Yes, it is. There is no syntax or semantic rule in the language that prevents that.
I am not aware of any "style" rule that you may be breaking, but in any case, another option is providing PYTHONPATH to the python interpreter.

Python Module Import: Single-line vs Multi-line

When importing modules in Python, what is the difference between this:
from module import a, b, c, d
and this
from module import a
from module import b
from module import c
from module import d
To me it makes sense always to condense code and use the first example, but I've been seeing some code samples out there dong the second. Is there any difference at all or is it all in the preference of the programmer?
There is no difference at all. They both function exactly the same.
However, from a stylistic perspective, one might be more preferable than the other. And on that note, the PEP-8 for imports says that you should compress from module import name1, name2 onto a single line and leave import module1 on multiple lines:
Yes: import os
import sys
No: import sys, os
Ok: from subprocess import Popen, PIPE
In response to #teewuane's comment (repeated here in case the comment gets deleted):
#inspectorG4dget What if you have to import several functions from one
module and it ends up making that line longer than 80 char? I know
that the 80 char thing is "when it makes the code more readable" but I
am still wondering if there is a more tidy way to do this. And I don't
want to do from foo import * even though I am basically importing
everything.
The issue here is that doing something like the following could exceed the 80 char limit:
from module import func1, func2, func3, func4, func5
To this, I have two responses (I don't see PEP8 being overly clear about this):
Break it up into two imports:
from module import func1, func2, func3
from module import func4, func5
Doing this has the disadvantage that if module is removed from the codebase or otherwise refactored, then both import lines will need to be deleted. This could prove to be painful
Split the line:
To mitigate the above concern, it may be wiser to do
from module import func1, func2, func3, \
func4, func5
This would result in an error if the second line is not deleted along with the first, while still maintaining the singular import statement
To add to some of the questions raised from inspectorG4dget's answer, you can also use tuples to do multi-line imports when folder structures start getting deeply nested or you have modules with obtuse names.
from some.module.submodule.that_has_long_names import (
first_item,
second_item,
more_imported_items_with_really_enormously_long_names_that_might_be_too_descriptive,
that_would_certainly_not_fit,
on_one_line,
)
This also works, though I'm not a fan of this style:
from module import (a_ton, of, modules, that_seem, to_keep, needing,
to_be, added, to_the_list, of_required_items)
I would suggest not to follow PEP-8 blindly. When you have about half screen worth of imports, things start becoming uncomfortable and PEP-8 is then in conflicts with PEP-20 readability guidelines.
My preference is,
Put all built-in imports on one line such as sys, os, time etc.
For other imports, use one line per package (not module)
Above gives you good balance because the reader can still quickly glance the dependencies while achieving reasonable compactness.
For example,
My Preference
# one line per package
import os, json, time, sys, math
import numpy as np
import torch, torch.nn as nn, torch.autograd, torch.nn.functional as F
from torchvision models, transforms
PEP-8 Recommandation
# one line per module or from ... import statement
import os
import json
import time
import sys
import math
import numpy as np
import torch
from torch import nn as nn, autograd, nn.functional as F
from torchvision import models, transforms
A concern not mentioned by other answers is git merge conflicts.
Let's say you start with this import statement:
import os
If you change this line to import os, sys in one branch and import json, os in another branch, you will get this conflict when you attempt to merge them:
<<<<<<< HEAD
import os, sys
=======
import json, os
>>>>>>> branch
But if you add import sys and import json on separate lines, you get a nice merge commit with no conflicts:
--- a/foo.py
+++ b/foo.py
### -1,2 -1,2 +1,3 ###
+ import json
import os
+import sys
You will still get a conflict if the two imports were added at the same location, as git doesn't know which order they should appear in. So if you had imported time instead of json, for example:
import os
<<<<<<< HEAD
import sys
=======
import time
>>>>>>> branch
Still, it can be worth sticking with this style for the occasions where it does avoid merge conflicts.
Imports should usually be on separate lines as per PEP 8 guidelines.
# Wrong Use
import os, sys
# Correct Use
import os
import sys
For more import based PEP 8 violations and fixes please check this out https://ayush-raj-blogs.hashnode.dev/making-clean-pr-for-open-source-contributors-pep-8-style.
Both are same.
Use from module import a, b, c, d.
If you want to import only one part of a module, use:
from module import a
If u want to import multiple codes from same module, use:
from module import a,b,c,d
No need to write all in separate lines when both are same.

Tool to help eliminate wildcard imports

I'm refactoring and eliminating wildcard imports on some fairly monolithic code.
Pylint seems to do a great job of listing all the unused imports that come along with a wildcard import, but what i wish it did was provide a list of used imports so I can quickly replace the wildcard import. Any quick ways of doing this? I'm about to go parse the output of pyLint and do a set.difference() on this and the dir() of the imported module. But I bet there's some tool/procedure I'm not aware of.
NB: pylint does not recommend a set of used imports. When changing this, you have to be aware of other modules importing the code you are modifying, which could use symbols which belong to the namespace of the module you are refactoring only because you have unused imports.
I recommend the following procedure to refactor from foo import *:
in an interactive shell, type:
import re
import foo as module # XXX use the correct module name here!
module_name = module.__name__
import_line = 'from %s import (%%s)' % module_name
length = len(import_line) - 3
print import_line % (',\n' + length * ' ').join([a for a in dir(module)
if not re.match('__.*[^_]{2}', a)])
replace the from foo import * line with the one printed above
run pylint, and remove the unused imports flagged by pylint
run pylint again on the whole code based, looking for imports of non existing sympols
run your unit tests
repeat with from bar import *
Here's dewildcard, a very simple tool based on Alex's initial ideas:
https://github.com/quentinsf/dewildcard
This is an old question, but I wrote something that does this based on autoflake.
See here: https://github.com/fake-name/autoflake/blob/master/autostar.py
It works the opposite way dewildcard does, in that it attempts to fully qualify all uses of wildcard items.
E.g.
from os.path import *
Is converted to
import os.path
and all uses of os.path.<func> are prepended with the proper function.

Categories

Resources