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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With