10

In python, if you need a module from a different package you have to import it. Coming from a Java background, that makes sense.

import foo.bar

What doesn't make sense though, is why do I need to use the full name whenever I want to use bar? If I wanted to use the full name, why do I need to import? Doesn't using the full name immediately describe which module I'm addressing?

It just seems a little redundant to have from foo import bar when that's what import foo.bar should be doing. Also a little vague why I had to import when I was going to use the full name.

kamasheto
  • 1,020
  • 6
  • 12
  • 1
    what do you mean by "need to import" ? Do you expect foo.bar to work without having to import it first ? How would you know then that foo is a module rather than a normal variable – mb14 Jul 06 '10 at 18:12
  • 4
    @mb14, in Java you can directly use classes in another package without importing by explicitly using the fully-qualified class name along with the package name in your code. For instance, you can refer to Java's List interface in your source as "java.util.List" or import it first then refer to it as simply "List". The way Python does it, to someone coming from Java, it feels like you're importing java.util.List, yet you still have to write out "java.util.List" rather than "List" in your code. – Jeff Jul 06 '10 at 18:25

8 Answers8

25

The thing is, even though Python's import statement is designed to look similar to Java's, they do completely different things under the hood. As you know, in Java an import statement is really little more than a hint to the compiler. It basically sets up an alias for a fully qualified class name. For example, when you write

import java.util.Set;

it tells the compiler that throughout that file, when you write Set, you mean java.util.Set. And if you write s.add(o) where s is an object of type Set, the compiler (or rather, linker) goes out and finds the add method in Set.class and puts in a reference to it.

But in Python,

import util.set

(that is a made-up module, by the way) does something completely different. See, in Python, packages and modules are not just names, they're actual objects, and when you write util.set in your code, that instructs Python to access an object named util and look for an attribute on it named set. The job of Python's import statement is to create that object and attribute. The way it works is that the interpreter looks for a file named util/__init__.py, uses the code in it to define properties of an object, and binds that object to the name util. Similarly, the code in util/set.py is used to initialize an object which is bound to util.set. There's a function called __import__ which takes care of all of this, and in fact the statement import util.set is basically equivalent to

util = __import__('util.set')

The point is, when you import a Python module, what you get is an object corresponding to the top-level package, util. In order to get access to util.set you need to go through that, and that's why it seems like you need to use fully qualified names in Python.

There are ways to get around this, of course. Since all these things are objects, one simple approach is to just bind util.set to a simpler name, i.e. after the import statement, you can have

set = util.set

and from that point on you can just use set where you otherwise would have written util.set. (Of course this obscures the built-in set class, so I don't recommend actually using the name set.) Or, as mentioned in at least one other answer, you could write

from util import set

or

import util.set as set

This still imports the package util with the module set in it, but instead of creating a variable util in the current scope, it creates a variable set that refers to util.set. Behind the scenes, this works kind of like

_util = __import__('util', fromlist='set')
set = _util.set
del _util

in the former case, or

_util = __import__('util.set')
set = _util.set
del _util

in the latter (although both ways do essentially the same thing). This form is semantically more like what Java's import statement does: it defines an alias (set) to something that would ordinarily only be accessible by a fully qualified name (util.set).

David Z
  • 128,184
  • 27
  • 255
  • 279
6

You can shorten it, if you would like:

import foo.bar as whateveriwant

Using the full name prevents two packages with the same-named submodules from clobbering each other.

Donald Miner
  • 38,889
  • 8
  • 95
  • 118
  • 1
    +1, This is the correct answer for what the OP is looking for. Perhaps edit to say "bar" instead of "whateveriwant"? That might make it more clear that it offers the sought-after functionality. – Cam Jul 06 '10 at 18:15
  • 3
    It comes close to the correct answer, but doesn't explain *why* Python exhibits this behavior. – Philipp Jul 06 '10 at 18:18
  • 1
    And it also is slightly more verbose than `from foo import bar`. "import foo.bar as bar" == 21 characters, "from foo import bar" == 19 characters. – JAB Jul 06 '10 at 18:24
  • 1
    @JAB but you can do "import foo.bar as mybar" to match nay internal naming you already have – Martin Beckett Jul 06 '10 at 19:35
  • 2
    @Martin Beckett: Only if `bar` is a module. the `import a.b as c` syntax doesn't work when b is a method or variable. In fact you can't import methods or variables using dot notation anyway. You have to use the `from ... import ...` syntax, or refer to the method or variable via the containing module name. – JAB Jul 06 '10 at 19:56
4

There is a module in the standard library called io:

In [84]: import io

In [85]: io
Out[85]: <module 'io' from '/usr/lib/python2.6/io.pyc'>

There is also a module in scipy called io:

In [95]: import scipy.io

In [96]: scipy.io
Out[96]: <module 'scipy.io' from '/usr/lib/python2.6/dist-packages/scipy/io/__init__.pyc'>

If you wanted to use both modules in the same script, then namespaces are a convenient way to distinguish the two.

In [97]: import this
The Zen of Python, by Tim Peters
...
Namespaces are one honking great idea -- let's do more of those!
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
3

You're a bit confused about how Python imports work. (I was too when I first started.) In Python, you can't simply refer to something within a module by the full name, unlike in Java; you HAVE to import the module first, regardless of how you plan on referring to the imported item. Try typing math.sqrt(5) in the interpreter without importing math or math.sqrt first and see what happens.

Anyway... the reason import foo.bar has you required to use foo.bar instead of just bar is to prevent accidental namespace conflicts. For example, what if you do import foo.bar, and then import baz.bar?

You could, of course, choose to do import foo.bar as bar (i.e. aliasing), but if you're doing that you may as well just use from foo import bar. (EDIT: except when you want to import methods and variables. Then you have to use the from ... import ... syntax. This includes instances where you want to import a method or variable without aliasing, i.e. you can't simply do import foo.bar if bar is a method or variable.)

JAB
  • 20,783
  • 6
  • 71
  • 80
  • `import foo.bar as bar` seems to be preferred over `from foo import bar` for some technical reason that I can't find any more. – Philipp Jul 06 '10 at 18:24
  • 1
    @Philipp: if so, that's news to me. – David Z Jul 06 '10 at 18:29
  • 1
    @Philipp: http://docs.python.org/py3k/howto/doanddont.html#from-module-import-name1-name2 No mentions of any preference there. In fact, you can't use the former in all cases, because it fails when you attempt to import methods or data members. – JAB Jul 06 '10 at 18:35
  • There has been something about modifying members in a special way. When using `from` and doing a certain modification in the imported module, AFAIR this change is not transferred to other modules that import the module. But probably I'm making this up and confusing something, I have been unable to find a source. – Philipp Jul 06 '10 at 21:56
  • 1
    @Philipp: You aren't wrong. Look at the page I linked to in a previous comment. But you shouldn't really be using `from` to import modules in the first place, because its primary purpose is for methods and variables/constants, which cannot be directly imported using the usual `import` syntax. – JAB Jul 07 '10 at 13:32
3

in Python, importing doesn't just indicate you might use something. The import actually executes code at the module level. You can think of the import as being the moment where the functions are 'interpreted' and created. Any code that is in the _____init_____.py level or not inside a function or class definition happens then.

The import also makes an inexpensive copy of the whole module's namespace and puts it inside the namespace of the file / module / whatever where it is imported. An IDE then has a list of the functions you might be starting to type for command completion.

Jim Carroll
  • 2,320
  • 17
  • 23
  • Note that when a module or package is imported multiple times, any executable code in the module or the package's `__init__.py` file will be executed only for the first import. Which is nice. – JAB Jul 06 '10 at 18:22
3

Part of the Python philosophy is explicit is better than implicit. Python could automatically import the first time you try to access something from a package, but that's not explicit.

I'm also guessing that package initialization would be much more difficult if the imports were automatic, as it wouldn't be done consistently in the code.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
1

Other than in Java, in Python import foo.bar declares, that you are going to use the thing referred to by foo.bar.

This matches with Python's philosophy that explicit is better than implicit. There are more programming languages that make inter-module dependencies more explicit than Java, for example Ada.

Using the full name makes it possible to disambiguate definitions with the same name coming from different modules.

mkneissl
  • 4,902
  • 2
  • 26
  • 28
1

You don't have to use the full name. Try one of these

from foo import bar

import foo.bar as bar

import foo.bar
bar = foo.bar

from foo import *

A few reasons why explicit imports are good:

  • They help signal to humans and tools what packages your module depends on.
  • They avoid the overhead of dynamically determining which packages have to be loaded (and possibly compiled) at run time.
  • They (along with sys.path) unambiguously distinguish symbols with conflicting names from different namespaces.
  • They give the programmer some control of what enters the namespace within which he is working.
ʇsәɹoɈ
  • 22,757
  • 7
  • 55
  • 61