Why can't I access a Python module?

Viewed 52

I have the following structure:

project
├── sum_package
│   └── sum_module.py
├── testing.py

I try to access sum_module.py from testing.py in two different ways:

First:

from sum_package import sum_module
sum_module.great_summation(1,2)

Second:

import sum_package
sum_package.sum_module.great_summation(1,2)

First works, second doesn't:

AttributeError: module 'sum_package' has no attribute 'sum_module'

Can someone explain why?

EDIT: tried adding __init__.py into either/both the package folder / the project folder, does not help.

EDIT 2: so it seems like the problem is $PYTHONPATH. I've tried adding my src (project) directory as PYTHONPATH, like this:

export PYTHONPATH = "$PWD"

while in src, but I still get the same error. What else am I missing?:)

1 Answers
project
├── __init__.py
|
├── sum_package
    ├── __init__.py
    |
│   └── sum_module.py
├── testing.py

The __init__.py files are required to make python treat directories containing the file as packages. Make your folder structure like this. In the simplest case, __init__.py can just be an empty file. Then try

testing.py

from sum_package import sum_module

sum_module.great_summation(1,2)
Related