I feel what I have is quite a simple question but I am struggling to make this work. I am using Bokeh 2.0.1 server to try and serve up an application, but I need to import some custom classes to help me interact with our internal API. The folder structure looks a bit like:
inside of main.py and since inside class_a.py it has:
from folder.subfolder_b.class_b import ClassB
It will import the classes correctly. However, I cannot get this to work, I keep getting ModuleNotFound errors.
How do I import classes from subfolders?
(The reason I want to do this, other than to keep the code tidy is that I am using existing classes from another project and I’d rather not edit them if possible)
Based on your description, I believe you are trying to import ClassB for use in ClassA. Correct?
If so you need to change the import statement in class_a.py to something like the following in this illustrative class based on the directory structure you’ve outlined. NB: folder.subfolder_b has been replaced with ..subfolder_b. The .. indicates that the relative path for the class should go up a directory.
class_a.py
from datetime import datetime
from ..subfolder_b.class_b import ClassB
class ClassA(object):
def __init__(self):
_methodname = self.__init__.__name__
self.ts = datetime.now()
self.b = ClassB()
print("{:}() INFO ClassA object @ {:}".format(_methodname, self.ts))
Starting with Bokeh 2.0 you can have Bokeh directory style apps be packages, but you need to follow standard Python conventions. Do the app folder and subfolders have __init__.py files (even empty ones) in them? Those are what allow a Python interpreter to map a filesystem directory structure in to a package hierarchy.