0

I have the following folder structure:

<project_name>

|__ <docs>

|__ <configs>

|__ <src>

.....|__  __init__.py

.....|__  utils.py

.....|__ <feature1>

..........|__ __init__.py

..........|__ feature1.py

where names enclosed in triangle brackets are folders.

From within feature1.py, I want to import utils.py. Since src is the highest level folder with an __init__.py file, I would have thought that that would be the package, meaning that I would need to do:

from src import utils

This does not work, and gives the error:

Exception has occurred: ModuleNotFoundError
No module named 'src'

However, when I run

from project_name.src import utils

it works fine. As I understand it, project_name is not a package, since it has no __init__.py file. Why is this required, and is there a way to get it to recognise src as the package?

Scott Vinay
  • 171
  • 1
  • 1
  • 6
  • 3
    _"As I understand it, `project_name` is not a package, since it has no `__init__.py` file"_. That's not true anymore. See [Is `__init__.py` not required for packages in Python 3.3+](https://stackoverflow.com/questions/37139786/is-init-py-not-required-for-packages-in-python-3-3/37140173#37140173) – Brian61354270 Feb 17 '21 at 14:11
  • Thanks. I read this, but it isn't then clear why project_name is a package, and not the folder above it, which is my Dropbox folder. – Scott Vinay Feb 17 '21 at 14:15
  • How are you running your python commands? Are you in project_name or elsewhere? What does `sys.path` give you? – astrochun Feb 17 '21 at 14:16
  • 1
    `project_name` may not be a package, but it may be a directory in your Python path that the import system will *look* in for packages. – chepner Feb 17 '21 at 14:21
  • @astrochun I am running the code from within feature1 (that is, I am running feature1.py which contains the import statements). sys.path does indeed seem to include Dropbox (which contains) project_name. I'm happy to considre this question answered. – Scott Vinay Feb 18 '21 at 15:23
  • Great. you probably had it pass through your PYTHONPATH environment variable. If you ended up using my below answer, could you mark it as the accepted one? Thanks. – astrochun Feb 18 '21 at 16:37

1 Answers1

2

It really comes down to how you install "project_name". Your setup.py can tell it where the packages are. Then __init__.py in each sub-folder will allow for it to be index.

An alternative approach is to use relative explicit path in your script.

from .. import utils

Keep in mind that the first . refers to feature1 so two dots goes to the src path.

astrochun
  • 1,642
  • 2
  • 7
  • 18