Why Is "Import *" Bad

Why is import * bad?

  • Because it puts a lot of stuff into your namespace (might shadow some other object from previous import and you won't know about it).

  • Because you don't know exactly what is imported and can't easily find from which module a certain thing was imported (readability).

  • Because you can't use cool tools like pyflakes to statically detect errors in your code.

Why is it bad practice to use from module import *?

This is what the Python style guide says about it:

Wildcard imports ( from <module> 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).

Why is using a wild card with a Java import statement bad?

The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need java.awt.Event, and are also interfacing with the company's calendaring system, which has com.mycompany.calendar.Event. If you import both using the wildcard method, one of these three things happens:

  1. You have an outright naming conflict between java.awt.Event and com.mycompany.calendar.Event, and so you can't even compile.
  2. You actually manage only to import one (only one of your two imports does .*), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.
  3. When you compile your code there is no com.mycompany.calendar.Event, but when they later add one your previously valid code suddenly stops compiling.

The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code that much easier. If you're just doing a quick one-off thing, there's nothing explicitly wrong, but future maintainers will thank you for your clarity otherwise.

What exactly does import * import?

The "advantage" of from xyz import * as opposed to other forms of import is that it imports everything (well, almost... [see (a) below] everything) from the designated module under the current module. This allows using the various objects (variables, classes, methods...) from the imported module without prefixing them with the module's name. For example

>>> from math import *
>>>pi
3.141592653589793
>>>sin(pi/2)
>>>1.0

This practice (of importing * into the current namespace) is however discouraged because it

  • provides the opportunity for namespace collisions (say if you had a variable name pi prior to the import)
  • may be inefficient, if the number of objects imported is big
  • doesn't explicitly document the origin of the variable/method/class (it is nice to have this "self documentation" of the program for future visit into the code)

Typically we therefore limit this import * practice to ad-hoc tests and the like. As pointed out by @Denilson-Sá-Maia, some libraries such as (e.g. pygame) have a sub-module where all the most commonly used constants and functions are defined and such sub-modules are effectively designed to be imported with import *. Other than with these special sub-modules, it is otherwise preferable to ...:

explicitly import a few objects only

>>>from math import pi
>>>pi
>>>3.141592653589793
>>> sin(pi/2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sin' is not defined

or import the module under its own namespace (or an alias thereof, in particular if this is a long name, and the program references its objects many times)

  >>>import math
>>>math.pi
>>>3.141592653589793
etc..


>>>import math as m #bad example math being so short and standard...
>>>m.pi
>>>3.141592653589793
etc..

See the Python documentation on this topic

(a) Specifically, what gets imported with from xyz import * ?

if xyz module defines an __all__ variable, it will import all the names defined in this sequence, otherwise it will import all names, except these which start with an underscore.

Note Many libraries have sub-modules. For example the standard library urllib includes sub-modules like urllib.request, urllib.errors, urllib.response etc. A common point of confusion is that

from urllib import *

would import all these sub-modules. That is NOT the case: one needs to explicitly imports these separately with, say, from urllib.request import * etc. This incidentally is not specific to import *, plain import will not import sub-modules either (but of course, the * which is often a shorthand for "everything" may mislead people in thinking that all sub-modules and everything else would be imported).

Python, is import * bad if I am importing all classes / functions from a file?

Yes. The problem is that may add more code in the future that could cause unexpected issues; such as naming conflicts.

I normally go with:

from myapp.models import MyModel
from myapp.models import MySecondModel

An alternative would be:

from myapp.models import (MyModel, MySecondModel)

Edit:

As @kalhartt pointed out you can also simply do.

from myapp import models

And then use models.MyModel etc if you have to import a lot of classes.

Python: Why should 'from module import *' be prohibited?

I believe by "in the middle of your program" you are talking about an import inside a function definition:

def f():
from module import * # not allowed

This is not allowed because it would make optimizing the body of the function too hard. The Python implementation wants to know all of the names of function-local variables when it byte-compiles a function, so that it can optimize variable references into operations on the (CPython) virtual machine's operand stack, or at least to local variable-slot operations rather than lookups in outer namespaces. If you could dump the entire contents of a module into a function's local namespace, then the compiler would have to assume that any name in the function might possibly refer to a module global, because the list of names brought in by from module import * is only known at runtime.

Putting from module import * in between top-level declarations is poor style, but it's allowed:

def f():
...

from module import *

def g():
...

EDIT April 2013: While looking into something else, I discovered that this restriction was introduced in Python 2.1, as a consequence of the "Nested Scopes" feature (PEP 227). Quoting from the link:

One side effect of the change is that the from module import * and exec statements have been made illegal inside a function scope under certain conditions. The Python reference manual has said all along that from module import * is only legal at the top level of a module, but the CPython interpreter has never enforced this before. As part of the implementation of nested scopes, the compiler which turns Python source into bytecodes has to generate different code to access variables in a containing scope. from module import * and exec make it impossible for the compiler to figure this out, because they add names to the local namespace that are unknowable at compile time. Therefore, if a function contains function definitions or lambda expressions with free variables, the compiler will flag this by raising a SyntaxError exception.

This clarifies the Python 3.x vs 2.x behavior discussed in the comments. It is always contrary to the language specification, but CPython 2.1 through 2.7 only issue an error for from module import * within a function if it might affect the compiler's ability to know whether a variable binds locally or in a containing scope. In 3.x it has been promoted to an unconditional error.

SON OF EDIT: ... and apparently flashk pointed this out years ago in another answer, quoting the same paragraph of "What's New in Python 2.1" yet. Y'all go upvote that now.

Use 'import module' or 'from module import'?

The difference between import module and from module import foo is mainly subjective. Pick the one you like best and be consistent in your use of it. Here are some points to help you decide.

import module

  • Pros:

    • Less maintenance of your import statements. Don't need to add any additional imports to start using another item from the module
  • Cons:

    • Typing module.foo in your code can be tedious and redundant (tedium can be minimized by using import module as mo then typing mo.foo)

from module import foo

  • Pros:

    • Less typing to use foo
    • More control over which items of a module can be accessed
  • Cons:

    • To use a new item from the module you have to update your import statement
    • You lose context about foo. For example, it's less clear what ceil() does compared to math.ceil()

Either method is acceptable, but don't use from module import *.

For any reasonable large set of code, if you import * you will likely be cementing it into the module, unable to be removed. This is because it is difficult to determine what items used in the code are coming from 'module', making it easy to get to the point where you think you don't use the import any more but it's extremely difficult to be sure.

Should wildcard import be avoided?

The answer to your question's title is "yes": I recommend never using from ... import *, and I discussed the reasons in another very recent answer. Briefly, qualified names are good, barenames are very limited, so the "third option" is optimal (as you'll be using qualified names, not barenames) among those you present.

(Advantages of qualified names wrt barenames include ease of faking/mocking for testing purposes, reduced to nullified risk of unnoticed errors induced by accidental rebinding, ability to "semi-fake" the top name in a "tracing class" for the purpose of logging exactly what you're using and easing such activities as profiling, and so forth -- disadvantages, just about none... see also the last-but-not-least koan in the Zen of Python, import this at the interactive interpreter prompt).

Equally good, if you grudge the 7 extra characters to say QtCore.whatever, is to abbreviate -- from PyQt4 import QtCore as Cr and from PyQt4 import QtGi as Gu (then use Cr.blah and Gu.zorp) or the like. Like all abbreviations, it's a style tradeoff between conciseness and clarity (would you rather name a variable count_of_all_widgets_in_the_inventory, num_widgets, or x? often the middle choice would be best, but not always;-).

BTW, I would not use more than one as clause in a single from or import statement (could be confusing), I'd rather have multiple statements (also easier to debug if any import is giving problem, to edit if you change your imports in the future, ...).

`from ... import` vs `import .`

It depends on how you want to access the import when you refer to it.

from urllib import request
# access request directly.
mine = request()

import urllib.request
# used as urllib.request
mine = urllib.request()

You can also alias things yourself when you import for simplicity or to avoid masking built ins:

from os import open as open_
# lets you use os.open without destroying the
# built in open() which returns file handles.

In Python, what happens when you import inside of a function?

Does it re-import every time the function is run?

No; or rather, Python modules are essentially cached every time they are imported, so importing a second (or third, or fourth...) time doesn't actually force them to go through the whole import process again. 1

Does it import once at the beginning whether or not the function is run?

No, it is only imported if and when the function is executed. 2, 3

As for the benefits: it depends, I guess. If you may only run a function very rarely and don't need the module imported anywhere else, it may be beneficial to only import it in that function. Or if there is a name clash or other reason you don't want the module or symbols from the module available everywhere, you may only want to import it in a specific function. (Of course, there's always from my_module import my_function as f for those cases.)

In general practice, it's probably not that beneficial. In fact, most Python style guides encourage programmers to place all imports at the beginning of the module file.



Related Topics



Leave a reply



Submit