Juan C
Juan C

Reputation: 6132

Calling a function from a module on a submodule

I'm quite new to working with more complex modules, but I think is about time to implement them in my work flow. Also, I don't come from a software engineering background so some of my languages might be inaccurate, please bear with me. My module folder structure is like this:

+-- module_name
|   +-- ml.py
|   +-- exp_an.py
|   +-- plotting.py
+-- etl
|   +-- machine_learning.py
|   +-- data_manipulation.py

The reason I have two folders is because the scripts directly on module_name are our personal library for use on most projects and the etl has code that is specific to this project.

In the beginning I had both folders on the same directory but I was having trouble importing from module_name to etl.

The thing is, in machine_learning.py I want to call a function from ml.py. I tried doing:

import sys
sys.append('../')
import module_name as mn

But this seems to bring some recursivity issues, because when I try to call mn.ml I get a mn has no attribute called ml error.

So, my question is, what is the right way to do this? Let's say I want to call a function called transform() that is inside ml.py in my machine_learning.py script. Is there a way to do this? Is there a better way to do this? Thanks

Upvotes: 2

Views: 2255

Answers (2)

skaill
skaill

Reputation: 51

In order for your directories to be interpreted as modules, you need to add __init__.py in each directory. Your directory structure will look like this.

+-- module_name
|   +-- __init__.py
|   +-- ml.py
|   +-- exp_an.py
|   +-- plotting.py
+-- etl
|   +-- __init__.py
|   +-- machine_learning.py
|   +-- data_manipulation.py

Then you'd use relative imports to get the modules. Example ->

# Inside machine_learning.py you are importing ml.py
import ..ml as ml

ml.transform()

Here is an example of a larger project. You can see how relative imports are used and the directories have their __init__.py.

https://github.com/TileThePlane/docusign-python-client

Upvotes: 2

John Gordon
John Gordon

Reputation: 33275

It sounds like you want to add the parent directory of module_name and etl (whatever that directory is) to your PYTHONPATH.

After doing that, you should be able to do all the imports you asked for.

To explain the mn has no attribute called ml error, that happened because you did not import ml. You just tried to use it as an attribute of mn, and you can't do that.

Upvotes: 0

Related Questions