Do the below 2 import statements have some difference? Or just the same thing?
from package import *
import package
from package import * imports everything from package into the local namespace; this is not recommended because it may introduce unwanted things (like a function that overwrites a local one). This is a quick and handy import tool, but if things get serious, you should use the from package import X,Y,Z, or import package syntax.
import package imports everything from package into the local package object. So if package implements the something() function, you will use it by package.something().
Also, another thing that should be talked about is the nested namespace case: suppose you have the function package.blabla.woohoo.func(), you can import package.blabla.woohoo and use package.blabla.woohoo.func(), but that is too complicated. Instead, the easy way to do it is from package.blabla import woohoo and then use woohoo.func() or from package.blabla.woohoo import func, and then use func(). I hope this makes sense. If it doesn't, here's a code piece to illustrate:
import package.blabla.woohoo
package.blabla.woohoo.func()
from package.blabla import woohoo
woohoo.func()
from package.blabla.woohoo import func
func()
Hope this helps :)
The difference is the use of a namespace for the package.
from package import *
class_in_package()
vs
import package
package.class_in_package()
Related
I am very new to python, I have a simple question.
For example
If I do
import A
then I can use A.b().
I am wondering, how to omit A in A.b()?
If you want to use b from module A:
from A import b
If you want to rename it:
from A import b as my_b
If you need several objects:
from A import b, c, d
If you need everything:
from A import *
About the import * option, please do read this post.
It's rather short, but tl;dr: do not import everything from a module by from A import *.
If you really need everything from the module, or a very big part of its content, prefer the normal import, possibly with renaming:
import numpy as np
import tkinter as tk
Since A is a module, you can do:
from A import b
b()
This question has already been answered, but one thing to note when using imports is that
from module import foo
and
import module
Are absolutely the same, as far as memory and performance is concerned. In either case, the module is compiled and loaded into sys.modules. The only difference is what is brought into your namespace. In the first case, it is foo. In the second case, it is module.
Since the other answers do not explain why using from module import * is bad, this is the reason: * will import everything into your namespace for direct use. This is not a good idea unless you know what you are doing. Name clashes are definitely possible, especially when importing multiple large modules.
This may be a matter of opinion, but I believe import module followed by module.foo() is safer and gives the reader a better idea about that method/attribute, where it came from, and what it is doing. Readability matters!
I have a small application that I would like to split into modules so that my code is better structured and readable. The drawback to this has been that for every module that I import using:
import module
I then have to use module.object for any object that I want to access from that module.
In this case I don't want to pollute the global namespace, I want to fill it with the proper module names so that I don't have to use
from module import *
in order to call an object without the module prepend.
Is there a means to do this that isn't consider to be poor use of from import or import?
Two reasonable options are to import with a shorter name to prepend. E.g.
import module as m
m.foo()
Or explicitly import names that you plan to use:
from module import (foo,bar)
foo()
You should avoid using an asterisk in your imports always. So to answer your question, I would say no, there isn't a better way than just:
import module
module.method()
OR
import really_long_module_name as mm
mm.method()
Take a look here at the pep8 guide "Imports" section:
https://www.python.org/dev/peps/pep-0008/#imports
Wildcard imports ( from import * ) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn't known in advance).
Specific is safer than globbing and I try to only import what I need if I can help it. When I'm learning a new module I'll import the whole thing and then once it's in a good state I go back and refactor by specifically importing the methods I need:
from module import method
method()
I would have to say that you should use the module's name. It's a better way of usage, and makes your code free of namespace confusions and also very understandable.
To make your code more beautiful, you could use the as import:
import random as r
# OR
from random import randint as rint
One solution that I think is not very beautiful, but works, that comes to mind, in case you don't want to pollute the global namespace, you can try to use the import statements, for example, inside functions.
For example:
>>> def a():
... from random import randint
... x = randint(0,2)
... print x
...
>>> a()
1
>>> randint(0,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'randint' is not defined
This way, the local namespace of the specific function is filled with the values from the module but the global one is clean.
Is there any performance difference between from package import * and import package?
No, the difference is not a question of performance. In both cases, the entire module must be parsed, and any module-level code will be executed. The only difference is in namespaces: in the first, all the names in the imported module will become names in the current module; in the second, only the package name is defined in the current module.
That said, there's very rarely a good reason to use from foo import *. Either import the module, or import specific names from it.
I'm a Python beginner and have just started using packages.
When you're calling a function after you've imported the package, do you always have to reference it to make it work, or is that just good practice?
For example, I'm working with the pandas package in ipython.
import pandas
import numpy as np
df = pandas.read_csv('/Users/admin/Documents/data.csv')
Do I always have to use the package name to call the function? If I don't, is it a best pract to always reference it?
If you adjust your import statement, then you don't need the package name.
For example:
from pandas import read_csv
import numpy as np
df = read_csv('/Users/admin/Documents/data.csv')
See this related question: Importing modules in Python - best practice
No, you don't have to; you can use the from [package] import [symbol] form, which will import the [symbol] in to the local namespace. That said, unless your app is heavily object oriented (as opposed to being module-centric), more often then not, it becomes both dangerous (accidentally reusing imported names locally) and confusing (hard to figure out where something is coming from and what it is intended to do) when you don't use package names.
If you have a local reference to an object, you can use that reference. If you do not, then you must reference the module first, then access it for the object.
The import statement in python has a few different forms. You could do this to only import the read_csv function:
from pandas import read_csv
df = read_csv('/path/to/file')
or this to import everything in the pandas module, so that you don't have to prefix it with pandas.:
from pandas import *
df = read_csv('/path/to/file')
This method is usually discouraged, though, because it makes it difficult to see where functions/classes/variables came from.
see http://docs.python.org/tutorial/modules.html for more info
If you change your import statement to
from pandas import *
you could then reference the function directly:
df = read_csv('/Users/admin/Documents/data.csv')
This will bring everything from the imported package into your current namespace. You can also specify piece-wise what should be imported. As discussed in the comments below, there are pros and cons to both approaches.
In my opinion, use whichever approach is least confusing in your current context. :)
Quick demonstration of the problem:
Define a module and name it functions.py containing: (this is just an example)
from __future__ import division
from scipy import *
def a():
return sin(1)
Now try to use it in a separate file as follows:
import functions as f
If you type f the pop-up list shows all scipy contents while it should be only a! See:
How to solve this?
This problem makes difficult to see what in the module functions exist.
Note:
1) Think that the module function will have numerous user-defined-functions.
2) There is no problem why scipy function are available globally. That's OK. The problem is why do they appear as member of f?!
It perhaps is a bug in Pyscripter, I am not sure!
Your module functions will contain references to everything imported globally and declared inside its scope.
As you're doing from scipy import * inside the module it will import everything, as it well should, and you will be able to access all the scipy functions from your functions module.
If you only wanted to see a() after importing functions, change it to this
# functions.py
def a():
from scipy import sin
return sin(1)
which will ensure that no references to your import will exist for the person importing your module.
Here's some reading on imports you can go through.
First of all, you should avoid import *, thus your code should look like:
from __future__ import division
from scipy import sin
def a():
return sin(1)
or
from __future__ import division
import scipy
def a():
return scipy.sin(1)
Another alternative is to add this to your module:
__all__ = ['a']