Relative imports in Python 3.0

Brian Allen Vanderburg II BrianVanderburg2 at
Wed Dec 17 13:38:38 CET 2008

nicholas.cole at wrote:
> Imagine a module that looks like
> ModuleDir
> In python 2.x I used to have tests at the end of each of my modules,
> so that module might look something like
> import a
>  ..........
>  ..........
> if __name__ == '__main__':
>    runtests()
> But under Python 3.0 this seems impossible.  For usual use import
> has to become the line:
> from . import a
> But if I use that form it is no longer possible to run as a
> standalone script without raising an error about using relative
> imports.
> I am sure I am not the first to run into this issue, but what is the
> solution?
> Best wishes,
> Nicholas
> --
Sorry for the duplicate, sent to wrong email.

Python 3 (and I think 2.6) now use absolute import when using a 'import 
blah' statement.

if ('.' in __name__) or hasattr(globals, '__path__'):
   from . import a
   import a

If '__name__' has a'.' then it is either a package or a module in a 
package, in which case relative imports can be used.  If it does not 
have a '.' it may still be a package but the '' file, in 
which case the module has a '__path__' attribute, so relative imports 
can be used.  Otherwise it is not a package or in a package so absolute 
imports must used.  Also, since it is not in a package it is assumed 
that it is top module (__main__) or possible module imported from the 
top that is not in a package, such as doing an 'import b', b would 
be a module but not a package so still probably need absolute imports, 
my guess anyway.

But I also think that 'from . import a' would be nice if it would work 
from non-packages as well, meaning just 'import a' if it is a non-package.

Brian A. Vanderburg II

More information about the Python-list mailing list