import in Python3.3
steve+comp.lang.python at pearwood.info
Wed Mar 27 00:06:02 CET 2013
On Tue, 26 Mar 2013 08:37:00 -0700, rocky wrote:
> And again, I get the impression that for the use case asked about, there
> isn't much ambiguity. If I am in mypackage.foo and I want to access
> mypackage.collections I should be able to say something like that
> without ambiguity or that much inference or directory searching.
And you can: either explicitly say
or use a relative import:
from . import collections
both of which only look inside mypackage.
> mypackage.colletions is not found inside the same directory as
> mypackage.foo, often I DON'T WANT Python to helpfully go searching
> around other places for it which sys.path will do.
With both solutions above, Python will not.
> Instead what I
> probably want is Python to give me an error.
> So again I come to import_relative,
> http://code.google.com/p/pyimport-relative/. And again, I wish this
> package didn't have to exist.
I'm not convinced it does. I don't understand the problem you are trying
to solve. "Provide relative imports" is not that problem, because the use-
case you give on the project page does not describe relative imports, as
they are understood in Python terminology.
The error message you get gives the game away:
ValueError: Attempted relative import in non-package
In a stand-alone module, you can't do a relative import because there is
no package structure, hence there is nothing to import relative to.
As I don't quite understand your use-case, I'm a shooting in the dark
here, but it seems to me that you could fix this entire problem by simply
using a package instead of a directory of stand-alone modules. A mere
directory of stand-alone modules should be merely loosely coupled, no
different from any other modules in sys.path. If your modules are tightly
coupled, they should go in a package.
One thing which would make import manipulations much easier would be if
import (and __import__) took an explicit search path, as opposed to
operating on a system-wide global. E.g.
import module using this_path
would be nice.
More information about the Python-list