Home › Python

ImportError: cannot import name 'soft_unicode' from 'markupsafe' (Python) — how to fix

Traceback (most recent call last):
  File "app.py", line 1, in <module>
    from flask import Flask
  ...
  File ".../site-packages/jinja2/utils.py", line 642, in <module>
    from markupsafe import soft_unicode
ImportError: cannot import name 'soft_unicode' from 'markupsafe' (.../site-packages/markupsafe/__init__.py)

Quick fix: Upgrade the package that imports it: pip install -U Jinja2 Flask (Jinja2 3.x no longer uses soft_unicode). If you can't upgrade, pin MarkupSafe: pip install "markupsafe==2.0.1".

What it means

soft_unicode was a deprecated alias of soft_str in MarkupSafe. MarkupSafe 2.1.0 removed it. Any library that still does from markupsafe import soft_unicode now fails at import time.

The importer is almost always Jinja2 2.x, which is installed by old versions of Flask, older Ansible, older Jupyter/nbconvert, dbt and similar tools that pinned Jinja2<3. Your project pins the old Jinja2 (or the old tool), but nothing pins MarkupSafe, so pip installs the newest one.

Find out who is importing it — the traceback shows the file:

pip show markupsafe jinja2
pip show -f jinja2 | head -3

Fix 1: upgrade Jinja2 (and whatever pins it)

Jinja2 3.x uses soft_str, so it works with current MarkupSafe:

pip install -U Jinja2

If pip refuses because another package requires Jinja2<3, upgrade that package too. For an old Flask 1.x app:

pip install -U Flask

Upgrading Flask from 1.x to 2.x+ also upgrades Werkzeug and itsdangerous; check your app still starts (see also the Werkzeug url_quote error, which is the same kind of problem).

Fix 2: pin MarkupSafe to 2.0.1

When you must keep the old stack (legacy app, locked tool version), pin the last MarkupSafe that still had soft_unicode:

pip install "markupsafe==2.0.1"

Make it permanent in requirements.txt so the next fresh install doesn't break again:

Flask==1.1.4
Jinja2==2.11.3
markupsafe==2.0.1

This is the usual fix for Docker images and CI jobs that suddenly broke without any code change: the build just pulled a newer MarkupSafe.

Fix 3: tools installed with pip (Ansible, dbt, etc.)

If the traceback points into a CLI tool's own environment, upgrade the tool rather than patching its dependencies:

pipx upgrade <tool>          # if installed with pipx
pip install -U <tool>        # inside its virtualenv

Installing each tool in its own virtualenv or with pipx stops one project's pins from breaking another.

Fix 4: your own code uses soft_unicode

Replace it with the new name:

from markupsafe import soft_str

value = soft_str(value)

Check

python -c "import jinja2, markupsafe; print(jinja2.__version__, markupsafe.__version__)"

Either Jinja2 3.x with any recent MarkupSafe, or Jinja2 2.x with MarkupSafe 2.0.1, imports without errors.

Last updated 2026-12-05.