Bokeh Server Import From Folder Structure

Hi all,

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:

| main.py
| folder
| > subfolder_a
| >> class_a.py
| > subfolder_b
| >> class_b.py

What I would like to do is include:

from folder.subfolder_a.class_a import ClassA

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)

Hi @Cuahchic

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.

1 Like

Thank you guys.

1 Like