Encountering an ImportError is a rite of passage for almost every Python developer, but few are as perplexing as ImportError: cannot import name 'box' from 'bokeh.Day to day, models'. This error typically stops a script dead in its tracks, leaving developers scratching their heads because the code often looks syntactically correct and matches older tutorials. Understanding why this happens requires a look at Bokeh’s evolution, specifically how its internal architecture shifted to support better performance and maintainability.
Understanding the Root Cause
The primary reason for this error is a major restructuring that occurred in Bokeh 3.Day to day, 0 (released April 2023). On the flip side, prior to this version, many layout and utility classes—including Box, Row, Column, and Spacer—lived directly inside the bokeh. models namespace. This was convenient but led to a bloated models module that mixed high-level layout logic with low-level property definitions.
Not the most exciting part, but easily the most useful.
To modernize the library, the core team moved layout-specific classes into a dedicated submodule: bokeh.models.layouts. As a result, from bokeh.models import Box ceased to work in version 3.0 and above. Still, if you are running a recent version of Bokeh but following a tutorial written for version 2. 4 or earlier, this import will fail immediately That's the part that actually makes a difference..
It is also worth noting that Box itself is somewhat of a legacy class. layoutsfunctions likerow, column, and gridplot. models.Still, layouts) or the higher-level bokeh. In modern Bokeh development, the preferred approach for creating flexible, CSS-flexbox-style layouts is using the **FlexBox** model (also located in bokeh.The old Box model mapped more closely to the deprecated CSS display: box specification, whereas FlexBox maps to the modern display: flex standard Not complicated — just consistent..
Real talk — this step gets skipped all the time.
The Immediate Fix: Updating Your Import Statement
The fastest way to resolve the crash is to update the import path to point to the new location. Change your import block from this:
# Old code (Bokeh < 3.0) - Causes ImportError
from bokeh.models import Box
To this:
# New code (Bokeh >= 3.0) - Correct import path
from bokeh.models.layouts import Box
Alternatively, if you are building a new layout from scratch, the modern best practice is to import FlexBox instead:
# Recommended modern approach
from bokeh.models.layouts import FlexBox
Pro Tip: If you are maintaining a codebase that must support both older and newer versions of Bokeh, you can use a try/except block to handle the import dynamically:
try:
# Try the new location first (Bokeh 3.0+)
from bokeh.models.layouts import Box
except ImportError:
# Fallback for older versions (Bokeh < 3.0)
from bokeh.models import Box
This pattern ensures your application remains backward compatible without requiring separate dependency branches.
Why FlexBox Is the Better Long-Term Solution
While fixing the import gets your code running, simply importing Box from the new location might not be the best architectural decision for new projects. The Box model is essentially a wrapper around the old CSS Flexible Box Layout Module (the 2009/2011 spec), which has limited browser support today and lacks the powerful alignment controls of the modern Flexbox spec Simple, but easy to overlook..
FlexBox exposes the full power of modern CSS Flexbox directly to Python. It allows you to control:
flex_direction: Row, column, row-reverse, column-reverse.justify_content: Flex-start, center, flex-end, space-between, space-around, space-evenly.align_items: Stretch, flex-start, center, flex-end, baseline.align_content: Controls spacing between lines in a multi-line flex container.gap/row_gap/col_gap: Native spacing between children without needing emptySpacerdivs.
Here is a comparison of how you would center a plot in a container using the old Box model versus the new FlexBox model.
Old Box Approach (Verbose, Limited Control):
from bokeh.models.layouts import Box
from bokeh.plotting import figure, show
p = figure(width=300, height=300)
p.circle([1, 2, 3], [4, 5, 6])
# Old Box requires manual CSS hacking or Spacers for centering
layout = Box(children=[p], css_classes=["custom-centering-class"])
show(layout)
Modern FlexBox Approach (Declarative, Powerful):
from bokeh.models.layouts import FlexBox
from bokeh.plotting import figure, show
p = figure(width=300, height=300)
p.circle([1, 2, 3], [4, 5, 6])
# Perfect centering with zero custom CSS
layout = FlexBox(
children=[p],
justify_content="center",
align_items="center",
width=600,
height=400
)
show(layout)
The FlexBox version is self-contained, readable, and renders consistently across all modern browsers without external stylesheets.
High-Level Layout API: The bokeh.layouts Module
For 90% of use cases, you do not need to interact with bokeh.layouts at all. ) and handle the boilerplate for you. The bokeh.Think about it: models. That's why layouts module provides high-level functions that automatically instantiate the correct underlying models (FlexBox, GridBox, etc. This is the most "Pythonic" way to compose dashboards And it works..
Common functions include:
row(*children, **kwargs): Arranges items horizontally.column(*children, **kwargs): Arranges items vertically.gridplot(children, **kwargs): Arranges items in a grid matrix.layout(children, **kwargs): A generic flexible layout builder.
Example using the high-level API:
from bokeh.layouts import row, column
from bokeh.plotting import figure, show
p1 = figure(width=250, height=250, title="Plot 1")
p1.line([1, 2, 3], [1, 2, 3])
p2 = figure(width=250, height=250, title="Plot 2")
p2.circle([1, 2, 3], [3, 2, 1])
# Nest rows and columns effortlessly
dashboard = column(
row(p1, p2), # Top row
row(p2, p1) # Bottom row
)
show(dashboard)
This approach abstracts away the model imports entirely. If you are not building custom Bokeh extensions or writing low-level serialization logic, stick to bokeh.layouts. It future-proofs your code against internal model changes Most people skip this — try not to. No workaround needed..
Troubleshooting Checklist: When the Fix Doesn't Work
If you have updated the import to from bokeh.models.layouts import Box (or FlexBox) and the error persists, run through this diagnostic checklist:
1. Verify Your Installed Version
Run this in your terminal or a notebook cell:
python -c "import bokeh; print(bokeh.__version__)"
If the output is 2.4.3 or lower, the layouts submodule does not exist in the same way, and Box should be in `bokeh.models
…Box should be in bokeh.Think about it: models directly, and the newer bokeh. models.layouts path will raise ImportError Simple, but easy to overlook..
python -m pip install --upgrade bokeh
After upgrading, restart the kernel or interpreter entirely — an already-imported bokeh module will not pick up the new files mid-session.
2. Check for Name Shadowing
Probably most common causes of a "perfectly correct" import failing is a local file or folder stealing the package name. If your project contains bokeh.py, or a directory called bokeh/, Python will import that instead of the installed library Most people skip this — try not to..
import bokeh
print(bokeh.__file__)
If the printed path points into your project directory rather than site-packages, rename the offending file or folder, and delete any stale __pycache__ directories left behind It's one of those things that adds up..
3. Confirm You Are in the Correct Environment
Jupyter notebooks, IDEs, and terminal shells frequently point at different
When the import error persists despite using the correct module path, the next place to look is the execution environment itself.
4. Confirm You Are Running Inside the Same Python Interpreter
Even if the version check shows a recent release, the interpreter that executes your script may differ from the one where the package was installed. In a typical development setup you might have:
- a system‑wide Python installation,
- a virtual environment created with
venvorconda, - a Jupyter kernel that was launched from a different environment than the one you used to
pip installBokeh.
To verify you are using the expected interpreter, add a quick sanity check at the top of the file that raises the error:
import sys
print("Python executable:", sys.executable)
print("Imported bokeh location:", sys.modules["bokeh"].__file__)
If the path points outside your project directory (e.g.And 11/site-packages/... Even so, , /usr/local/lib/python3. ) and you expected a path inside a virtual environment, activate the correct environment before launching the script or notebook Not complicated — just consistent..
5. Restart the Kernel / REPL
In interactive environments such as Jupyter Notebook, IPython, or a plain REPL, modules are cached after the first import. Changing the installation (for example, by upgrading Bokeh) does not automatically refresh the already‑loaded module. This guarantees that the new version of bokeh.models.The safest remedy is to restart the kernel or quit and re‑enter the interpreter. layouts is imported fresh It's one of those things that adds up. But it adds up..
6. Verify That the Package Is Actually Installed in the Active Environment
Sometimes the upgrade command is run in one environment while the code runs in another. Run the following command inside the same shell or notebook kernel that you use to execute your dashboard code:
python -c "import bokeh, inspect, sys; \
print('Bokeh version:', bokeh.__version__); \
print('Layout module file:', inspect.getfile(bokeh.models.layouts.Box))
If the printed module file points to a location that does not contain a layout.py (or if the import fails), the package installation is mismatched. Also, re‑installing with the same interpreter, e. g.
python -m pip install --upgrade --force-reinstall bokeh
will resolve the discrepancy Took long enough..
7. Watch Out for Conditional Imports
Certain libraries (e.Which means g. , tornado, asyncio) may alter sys.Plus, path or replace the standard import mechanism. If you have custom import hooks or monkey‑patch importlib, the normal import resolution can be bypassed, causing the Box symbol to be invisible even though the package is present. In such cases, temporarily disabling the hook and performing a plain import is the quickest way to confirm whether the problem lies in the import machinery rather than the Bokeh installation itself Practical, not theoretical..
Best‑Practice Summary for Layout Construction
- Prefer the high‑level
bokeh.layoutsAPI –row,column,gridplot, andlayouthide the underlying model objects and keep your code resilient to internal changes. - Keep imports minimal –
from bokeh.layouts import row, column(or the fullbokeh.models.layoutsif you need a specific layout class) is sufficient; avoid pulling inbokeh.modelsunless you are writing low‑level extensions. - Work in isolated environments – virtual environments, conda channels, or Docker containers eliminate version drift and name‑shadowing issues.
- Restart after dependency changes – always refresh the kernel or process after installing or upgrading packages.
- Use explicit version pinning – in
requirements.txtorenvironment.yml, lock the Bokeh version that your dashboard has been tested against. This makes reproducibility easier and prevents accidental breaking changes.
Conclusion
The “most Pythonic” way to compose dashboards in Bokeh is to rely on the bokeh.layouts module, which abstracts away the low‑level model hierarchy and shields your code from internal API churn. When you encounter an ImportError for Box or FlexBox, follow the diagnostic