tags:

views:

282

answers:

8

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.

+5  A: 

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.

orangeoctopus
+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
It comes close to the correct answer, but doesn't explain *why* Python exhibits this behavior.
Philipp
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
@JAB but you can do "import foo.bar as mybar" to match nay internal naming you already have
Martin Beckett
@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
+3  A: 

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
`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
@Philipp: if so, that's news to me.
David Zaslavsky
@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
+1 for mentioning accidental namespace conflicts!
EOL
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
@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
@JAB: Oh yes, that's indeed what I meant, thanks.
Philipp
+1  A: 

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
+3  A: 

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
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
+3  A: 

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
+3  A: 

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
+1  A: 

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.
Forest
+21  A: 

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. Since Python is an interpreted language with dynamic resolution, there's no compiler to go out and look up the code of any util.set module. What happens in Python is that the interpreter looks for a package named util with a module named set inside it and loads the package and module, and in the process, it actually creates an object named util with an attribute named set. (That's right, packages and modules are actual first-class objects in Python.) You could think of the above statement as

util = __import__('util.set')

where the function __import__ produces an object which has an attribute called set. In fact, that's actually what happens when you import a module - see the documentation for __import__. So you see, when you import a Python module, what you really get is just an object corresponding to the top-level package, util, and in order to get access to set you need to go through that.

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 does; it defines an alias (set) to something that would ordinarily only be accessible by a fully qualified name (util.set).

David Zaslavsky
This explains it pretty well, thanks. I just feel there's a typo somewhere in your answer? You mention importing is similar to: `util = __import__('util.set')` then you go to mention `import util.set as set` is similar to `set = __import__('util.set')`?
msakr
Good point. I went back and checked the documentation and I think it should be more accurate now.
David Zaslavsky