3

I need to pickle a python class I have instantiated and therefore need to use relative paths. I am using Python Version 3.6.6. Here is an example of how the project structure and code looks like:

modelling/
    test.py
    mod1/
        __init__.py
        classic_mod.py

init.py

from .classic_mod import classic

classic_mod.py

class classic:

    def __init__(self, input_string):
        self.input_string = input_string
        print(self.input_string)

    def log_info(self):
        print(self.input_string)

test.py

from .mod1 import classic_mod
from sklearn.externals import joblib

model = classic_mod.classic("Hello World!")
joblib.dump(model, "model.pkl")

If I use absolute paths I get problems when I load the pickle file into python in another folder. When I run test.py I get an error saying:

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    from .mod1 import classic_mod
ModuleNotFoundError: No module named '__main__.mod1'; '__main__' is not a package

How can I solve this import error and at the same time pickle the class so I can use somewhere else?

danielo
  • 770
  • 2
  • 13
  • 32

1 Answers1

3

You need to wrap up your code in a package in order to use relative imports. Set a setup script and use the pip -e install flag to install it as a development module. This is a very good in-depth explanation of the problem you are facing.

Alexander Ejbekov
  • 5,594
  • 1
  • 26
  • 26