Cupitor
Cupitor

Reputation: 11657

Accessing a module that belongs to a parent directory or to the module's sibling in python

I have already browsed all the topics close to this but couldn't find the answer to my question.

I have the following directory structure

--Codes +------mod_welch.py +------__init__.py +------Toy_Model ++---------__init__.py ++---------linear_filter.py

Both of __init__.py's are empty and I am trying to access to mod_welch.py in the body of linear_filter.py with no success. When I want to use realtive access to upper folders as from ..mod_welch import welch where welch is a function inmod_welch I receive:

ValueError: Attempted relative import in non-package 

What am I doing wrong?

Upvotes: 1

Views: 43

Answers (1)

Konrad Talik
Konrad Talik

Reputation: 916

In genereal, your module should be import-ed somewhere and then used. Error message that you're receiving suggests that there is unusual execution method of module code. I suspect that youre testing your code by runnig python linear_filter.py (it gives the same error). Thats not the way.

As I said above you need to actually use your module if you want to test its functionality. To do that, you can import your module in another module or main script, for example:

from Codes.Toy_Model.linear_filter import some_method
if __name__ == '__main__':
    print(some_method())

Where some_method is defined in linear_filter.py as:

from Codes.mod_welch import welch
def some_method()
    welch()

If that's not the case then please provide additional information about what is an usage (execution) method of your module -- which script are you running and how. Any sys.path.append magic etc. are important here too.

Upvotes: 1

Related Questions