How do I import from a file in the current directory in Python 3?

user5076297 picture user5076297 · Jul 7, 2015 · Viewed 59.7k times · Source

In python 2 I can create a module like this:

parent
->module
  ->__init__.py (init calls 'from file import ClassName')
    file.py
    ->class ClassName(obj)

And this works. In python 3 I can do the same thing from the command interpreter and it works (edit: This worked because I was in the same directory running the interpreter). However if I create __ init __.py and do the same thing like this:

"""__init__.py"""
from file import ClassName

"""file.py"""
class ClassName(object): ...etc etc

I get ImportError: cannot import name 'ClassName', it doesn't see 'file' at all. It will do this as soon as I import the module even though I can import everything by referencing it directly (which I don't want to do as it's completely inconsistent with the rest of our codebase). What gives?

Answer

Dunes picture Dunes · Jul 7, 2015

In python 3 all imports are absolute unless a relative path is given to perform the import from. You will either need to use an absolute or relative import.

Absolute import:

from parent.file import ClassName

Relative import:

from . file import ClassName
# look for the module file in same directory as the current module