En Sat, 23 May 2009 12:32:24 -0300, LittleGrasshopper <seattleha...@yahoo.com> escribió:

On May 22, 12:42 am, "Gabriel Genellina" <gagsl-...@yahoo.com.ar>
wrote:
En Wed, 20 May 2009 20:18:02 -0300, LittleGrasshopper  
<seattleha...@yahoo.com> escribió:

> It appears that either absolute imports (or my brain) aren't working.
> Given a module string.py which is in the same directory as a.py:

> #File a.py
> from __future__ import absolute_import
> import string
> print string # Module imported is string.py in current directory, not
> standard library module

absolute_import helps with imports inside a package (those are "relative"   imports, relative to the package). If a module is located in a directory   listed in sys.path, an absolute import will find it. I don't think there  
is a way to avoid shadowing a standard module (other than ensuring the  
standard directories come first in sys.path).

You are right. If you have a directory in your PYTHONPATH before the
standard library directories that has a string module, for example,
absolute_import will not help you. I was getting confused by the fact
that when I print sys.path from the python shell, the first entry is
an empty string.
This empty string must denote the current directory though, because:

['', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/ ...]

When I have this sys.path, doing an "import string" from a module
where I have absolute imports enabled will still import the string
module in the package (which also means it is in the same directory in
this case.)

Mmm, I don't understand this. Do you mean that the current directory is a package (that is, it contains an __init__.py file? And the main script is there? Then, from Python's POV, it is NOT a package; packages are recognized only at import time; if you execute a script that happens to be inside a package directory, Python is not aware of the "packageness" of such directory.
In that case, all imports are absolute.
The current directory should not be a package (at least, not a package accessible from sys.path), nasty things may happen.

So I think my string.py is being imported not because it
is in the same package, but because the home directory is searched
first.

Yes.

The empty string doesn't make much sense though (at least in a
Unix system, you would imagine it would be something like './') but I
guess that synce Python is platform independent, the empty string is
taken to denote the current directory.

Maybe you're surprised, but I don't think it's strange at all. Nobody writes open("./foo.txt") instead of open("foo.txt"), and os.path.normpath("./foo.txt") is actually "foo.txt". Having no path specification means "use the current directory" (at least in all OS that I know of, where "process' current directory" makes any sense)

--
Gabriel Genellina

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to