Search code examples
python-3.xpython-import

How to import classes and function from files within the same dir as main.py in Python 3.9?


I am struggling with importing local source files that reside in the same directory as main.py in Python 3.9. I had it working before but couldn't tell why it was working. After a while it stopped working.

I created a minimal example to reproduce the problem with the structure shown below.

I have read some available answers that suggest using from . import car in main.py which resulted in the following Error:

(venv) [.../pyimport_example/productname]  python3 ./main.py
Traceback (most recent call last):
  File "/Users/myUser/pyimport_example/productname/./main.py", line 1, in <module>
    from . import car
ImportError: attempted relative import with no known parent package

Got the same error when using from .car import Car

I have also tried to run main.py as a module as suggested in "Relative imports in Python 3:

(venv) [.../pyimport_example/productname] python3 -m main.py
Traceback (most recent call last):
  File "/usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 188, in _run_module_as_main
    mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
  File "/usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 111, in _get_module_details
    __import__(pkg_name)
  File "/Users/myUser/pyimport_example/productname/main.py", line 2, in <module>
    from .car import Car
ImportError: attempted relative import with no known parent package

The answer to "Relative imports in Python 3 seems to focus on the case where one want to run a python file as a script inside a package, which is not the problem I am having.

My sample project

pyimport_example
├── README.md
├── productname
│   ├── __init__.py
│   ├── car.py
│   └── main.py
└── venv
    ├── bin
    ├── include
    ├── lib
    └── pyvenv.cfg

content of main.py

from .car import Car


def main():
    print("Maria ist cool.")

    mycar = Car("Ford", "Mustang", "1966")
    mycar.print_car()


if __name__ == '__main__':
    main()

contents of car.py

class Car:
    def __init__(self, make, model, year_manufacture):
        self.make = make
        self.model = model
        self.year_manufacture = year_manufacture

    def print_model(self):
        print("{0} {1} {2}".format(self.year_manufacture, self.make, self.model))

Is there a fix without modifying the system path?


Solution

  • You have to modify your __init__.py-File.

    In the folder productname you wanna specify what imports you can run from a module on the same level:

    from .car import *
    

    Now you should be able to import your file into your main.py with:

    from car import Car