68

In Python, what exactly does import * import? Does it import __init__.py found in the containing folder?

For example, is it necessary to declare from project.model import __init__, or is from project.model import * sufficient?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
ensnare
  • 40,069
  • 64
  • 158
  • 224
  • 2
    `from yadda.yadda import *` is most useful when hacking at things in the Python command line, e.g. when you're using Python as a calculator and you just type out `from math import *`. In a module, it's asking for trouble. Also, if you import a single-file module (as opposed to a directory), `from ... import *` won't import symbols whose names begin with `_`. – Mike D. Mar 02 '10 at 03:51
  • Related: *[How does Java import work?](https://stackoverflow.com/questions/12620369/how-does-java-import-work)*. – Peter Mortensen Nov 18 '22 at 00:40

6 Answers6

76

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).

mjv
  • 73,152
  • 14
  • 113
  • 156
  • 30
    The advantage of `from X import *` is that it allows you to be lazy. The problem of it is that it will bite you in the ass for lazy :) – Esteban Küber Mar 02 '10 at 04:14
  • 1
    Some modules (like [`pygame`](http://www.pygame.org/docs/ref/locals.html), but many others) have a special submodule that is intended to be imported as `*`. Such special modules usually have commonly used constants or functions. – Denilson Sá Maia Jan 25 '11 at 01:55
  • So basically I can import everything without getting a name space collision if i use `import math` as opposed to `from math import*` ? – the_prole Nov 16 '14 at 13:59
  • 1
    @the_prole Indeed. `import math` ensures that there would be no name conflicts; to access any method or object from math in the code you will however need to prefix it with `math.` as in `math.pi` or `math.sin(...)`. With the `from math import *` there will be no need for the `math.` prefix (in fact that would work) but on the other there may be namespace collisions. – mjv Nov 17 '14 at 04:14
  • 3
    This answer is incomplete/incorrect/misleading. `import *` does not import submodules, which is often the cause of confusion. For example, after `from tkinter import *` you still have to do `from tkinter import messagebox` because `messagebox` is a submodule of tkinter. – Aran-Fey Jun 06 '18 at 11:55
  • @Aran-Fey Thank you for the feedback. I added a note to dispel this common misconception. Incidentally this behavior [of not loading/importing] the sub-modules is not specific to `import *` but indeed this is where it may be expected because of the usual meaning ascribed to `*`. – mjv Jun 18 '18 at 22:52
  • 2
    Well, it's a bit more complicated than that. `import *` won't automatically load submodules that haven't been loaded yet, unless those submodules are listed in `__all__`, but it will import any submodules that happen to have already been loaded (usually due to other imports loading them). This can cause really weird bugs where the behavior of `import *` depends on import ordering and what code paths have been taken so far. – user2357112 Jun 18 '18 at 22:56
15

It import (into the current namespace) whatever names the module (or package) lists in its __all__ attribute -- missing such an attribute, all names that don't start with _.

It's mostly intended as a handy shortcut for use only in interactive interpreter sessions: as other answers suggest, don't use it in a program.

My recommendation, per Google's Python style guide, is to only ever import modules, not classes or functions (or other names) from within modules. Strictly following this makes for clarity and precision, and avoids subtle traps that may come when you import "stuff from within a module".

Importing a package (or anything from inside it) intrinsically loads and executes the package's __init__.py -- that file defines the body of the package. However, it does not bind the name __init__ in your current namespace (so in this sense it doesn't import that name).

root-11
  • 1,727
  • 1
  • 19
  • 33
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • So basically I can import everything without getting a name space collision if i use `import math` as opposed to `from math import*` ? – the_prole Nov 16 '14 at 13:59
5

Here is a nice way to see what star / asterisk ( * ) has imported from a module:

before = dir()
from math import *
after = dir()
print(set(after) - set(before))

returns:

{'modf', 'pow', 'erfc', 'copysign', 'sqrt', 'atan2', 'e', 'tanh', 'pi', 'factorial', 'cosh', 'expm1', 'cos', 'fmod', 'frexp', 'log', 'acosh', 'sinh', 'floor', 'isclose', 'lgamma', 'ceil', 'gcd', 'ldexp', 'hypot', 'radians', 'atan', 'isnan', 'atanh', 'before', 'isinf', 'fabs', 'isfinite', 'log10', 'nan', 'tau', 'acos', 'gamma', 'asin', 'log2', 'tan', 'degrees', 'asinh', 'erf', 'fsum', 'inf', 'exp', 'sin', 'trunc', 'log1p'}

I was working with my own module, importing everything explicitly but the list of stuff to import was getting too long. So, had to use this method to get a list of what * had imported.

cardamom
  • 6,873
  • 11
  • 48
  • 102
4

Yes, it does. It imports everything (that is not a private variable, i.e.: variables whose names start with _ or __), and you should try not to use it according to "Properly importing modules in Python" to avoid polluting the local namespace.

It is enough, but generally you should either do import project.model, which already imports __init__.py, per "Understanding python imports", but can get too wordy if you use it too much, or import project.model as pm or import project.model as model to save a few keystrokes later on when you use it.

Follow Alex's advice in "What exactly does "import *" import?"

Community
  • 1
  • 1
Esteban Küber
  • 36,388
  • 15
  • 79
  • 97
  • 7
    Good recommendation, but imprecise information: `from foo import *` does **not** "import everything" -- it imports names listed in the module's `__all__` attribute, or, missing that attribute, _non-private_ names (excluding names starting with `_`). – Alex Martelli Mar 02 '10 at 03:50
  • @Alex, good point. Would you like to expand on it, or would you prefer that I do it? – Esteban Küber Mar 02 '10 at 04:13
  • I've already expanded on it -- see my answer to this question. – Alex Martelli Mar 02 '10 at 04:16
4

If project.model is a package, the module referred to by import project.model is from .../project/model/__init__.py. from project.model import * dumps everything from __init__.py's namespace into yours. It does not automatically do anything with the other modules in model. The preferred style is for __init__.py not to contain anything.

Never ever ever ever ever use import *. It makes your code unreadable and unmaintainable.

Mike Graham
  • 73,987
  • 14
  • 101
  • 130
2

If the module in question (project.model in your case) has defined a list of stings named __all__, then every named variable in that list is imported. If there is no such variable, it imports everything.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304