Creating classes and objects more than once?

Carl Banks pavlovevidence at gmail.com
Sat Nov 29 00:51:59 EST 2008


On Nov 28, 2:59 pm, Ben Finney <bignose+hates-s... at benfinney.id.au>
wrote:
> Carl Banks <pavlovevide... at gmail.com> writes:
> > On Nov 28, 3:15 am, Ben Finney <bignose+hates-s... at benfinney.id.au>
> > wrote:
> > > This is resolved in the Python 2.x series by implementing PEP 328
> > > <URL:http://www.python.org/dev/peps/pep-0328/>, such that the
> > > search path for ‘import’ does *not* contain the current directory,
> > > and requiring relative-to-the-current-directory imports to be
> > > explicitly requested.
>
> > PEP 328 doesn't say anything about that. Using Python 2.5, which PEP
> > 328 claims implements this change, I see the same behavior that
> > Victor Kerkez sees. My sys.path[0] is still the empty string,
> > meaning that Python does start its import search from the current
> > directory.
>
> In Python 2.5, the PEP is implemented to the point that the absolute
> import behaviour is available by adding a ‘from __future__ import
> absolute_import’. Without that, yes, you will see the same behaviour
> as reported by Victor.

I see the same behavior as Viktor reports regardless of whether I
disable relative imports or not.

Absolute versus relative imports don't have anything to do with the
issue here.  PEP 328 concerns itself with imports relative to the
executing module in package space.  It has nothing to do with imports
relative to the current directory in filename space.

If the string "" is in sys.path, then imports relative to the current
directory (including changes to the current directory made by
os.chdir) will work, even if relative imports are disabled.

Try this test with Python 2.5.  (sh command lines to set up the
environment shown.)

$ mkdir foo
$ mkdir bar
$ touch bar/baz.py
$ cat > foo/script.py <<EOF

from __future__ import absolute_import

import sys, os
sys.path.insert(0,"")
os.chdir('../bar')
import baz

EOF
$ cd foo
$ python2.5 script

If your claim that importing from the current directory is disabled
when "from __future__ import absolute_import" is issued were true,
then the import of baz module would raise an exception.  It doesn't
for me.

On further investigation, I found was that sys.path[0] is "" whenever
it uses an interactive interpreter or the -c switch is used, but is
the directory of the script file whenever python is given a script
file.  Which means, by default, importing from the current directory
is disabled for scripts, but enabled for interactive work and the -c
switch.  This is regardless of whether relative imports are disabled
or not.


Carl Banks



More information about the Python-list mailing list