From PEP 328:
Relative imports use a module's __name__
attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__
') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
Clarification: The __name__
attribute will usually be the path a module has when it's being imported, e.g. in foo/bar.py, provided foo was the top-level package, __name__
would be 'foo.bar'. In the special case of a .py file you're running directly, __name__
evaluates to '__main__'
, which means relative imports will not work.