Home > Back-end >  Python saying file does not exist when importing but clearly does
Python saying file does not exist when importing but clearly does

Time:06-16

I am writing a simple pygame name generator for a little project and am trying to import a function I made but it says it does not exist. You can see: here that my from and imports are correct. The script that runs is fantasy name generator yet this error (in the screenshot) is produced. Any help would be appreciated, thanks.

My folder structure:

This image is of my folder structure

CodePudding user response:

generate_name.py is in a deeply nested package alongside the other module. Python 3 uses absolute imports by default, relative imports must be performed explicitly.

The relative import you'd want here is (note leading . indicating a relative name):

from .prefix_code_gen import prefix_code_gen

The absolute import path would match the same one you used for generate_name if you wanted to use it:

from functional.generators.prefix_code_gen import prefix_code_gen

I'm inclined to favor the relative import, since it will continue to work even if a refactoring changes the absolute path, as long as the two modules are still installed under the same package directory.

  • Related