If Python throws “can not import name escape from jinja2,” the Jinja2 version you’re using no longer supports that function. This error typically appears when you try to import the escape function from Jinja2, but it has been moved or removed in newer releases. You might see this in older codebases or tutorials that haven’t been updated.
Don’t worry—this is a common issue with a straightforward fix. In this guide, we’ll walk through why this happens, how to fix it, and how to prevent it in the future. Let’s get started.
What Causes “Can Not Import Name Escape From Jinja2”
The error occurs because Jinja2 changed its module structure over time. In older versions (like 2.x), the escape function was directly available from jinja2. Starting with Jinja2 3.0, the function was moved to markupsafe library.
When you run code that tries from jinja2 import escape with a newer Jinja2 version, Python can’t find it. That’s when you see the ImportError.
Common Scenarios Where This Error Appears
- Running legacy Flask or Django applications
- Using outdated tutorials or documentation
- Mixing different package versions in a virtual environment
- Upgrading Jinja2 without updating your import statements
Can Not Import Name Escape From Jinja2: The Fix
Here are three reliable ways to resolve this error. Choose the one that best fits your situation.
Method 1: Use Markupsafe Instead
The most modern solution is to import escape from markupsafe. This library is a dependency of Jinja2, so it’s likely already installed.
- Open your Python file or terminal
- Replace
from jinja2 import escapewithfrom markupsafe import escape - Test your code again
Example:
from markupsafe import escape
This works with Jinja2 3.0 and above. The escape function behaves identically—it HTML-escapes strings to prevent XSS attacks.
Method 2: Downgrade Jinja2
If you can’t change your codebase, you can install an older Jinja2 version that still has escape.
- Run
pip install jinja2==2.11.3 - Verify with
pip show jinja2 - Your original import should now work
Be aware: downgrading might break other dependencies that require newer Jinja2 features.
Method 3: Use Jinja2’s Markup Class
Instead of escape, you can use the Markup class from Jinja2 itself. This is another valid approach.
- Import
from jinja2 import Markup - Use
Markup.escape(text)instead ofescape(text) - Or use
Markup(text).striptags()for other operations
This method keeps everything within Jinja2 and avoids external dependencies.
Why Did Jinja2 Remove The Escape Function?
The Jinja2 team moved escape to markupsafe for better separation of concerns. Markupsafe handles safe string markup, while Jinja2 focuses on templating. This change also reduces Jinja2’s footprint.
If you’re upgrading from an older version, you’ll need to update your imports. The function itself hasn’t changed—only its location.
Checking Your Jinja2 Version
To see which version you have:
pip show jinja2
If it shows 3.0 or higher, you need to use markupsafe. If it’s 2.x, your original import should work.
Step-By-Step Troubleshooting Guide
Follow these steps to diagnose and fix the error quickly.
Step 1: Identify The Error Source
- Look at the full traceback in your terminal
- Find the exact line where the import fails
- Check if it’s in your code or a third-party library
Step 2: Check Package Versions
- Run
pip list | grep -i jinja(Linux/Mac) orpip list | findstr jinja(Windows) - Note the Jinja2 and markupsafe versions
- If markupsafe is missing, install it:
pip install markupsafe
Step 3: Update Your Import Statement
Change your code to use markupsafe:
from markupsafe import escape
Then test your application again.
Step 4: Verify The Fix
- Run a simple test:
print(escape("")) - It should output:
<script>alert('xss')</script> - If you see the original string, the import worked correctly
Common Mistakes When Fixing This Error
Avoid these pitfalls to save time.
Mistake 1: Only Upgrading Jinja2 Without Updating Imports
Many developers upgrade Jinja2 to get new features but forget to change their import statements. Always update both together.
Mistake 2: Installing Markupsafe But Not Using It
Even if markupsafe is installed, your code won’t work unless you change the import path. The error persists if you keep from jinja2 import escape.
Mistake 3: Confusing Escape With Other Functions
Jinja2 has other functions like safe and e. Don’t mix them up. The escape function specifically HTML-escapes strings.
How To Prevent This Error In Future Projects
Follow these best practices to avoid the same issue.
Use Virtual Environments
Always create a virtual environment for each project. This isolates dependencies and prevents version conflicts.
python -m venv myenv
source myenv/bin/activate (Linux/Mac)
myenv\Scripts\activate (Windows)
Pin Your Dependencies
Use a requirements.txt file to lock package versions. This ensures everyone on your team uses the same versions.
pip freeze > requirements.txt
Keep Dependencies Updated
Regularly check for updates and test your code. Use tools like pip-review to see what’s outdated.
Read Documentation
When upgrading a major version, always read the changelog. Jinja2’s documentation clearly explains breaking changes like this one.
Real-World Example: Fixing A Flask Application
Let’s walk through a real scenario. You have a Flask app that uses escape from Jinja2.
Original code:
from flask import Flask, request
from jinja2 import escape
app = Flask(__name__)
@app.route('/')
def home():
name = request.args.get('name', '')
return f'Hello, {escape(name)}!'
After upgrading Jinja2, you get the error. Here’s the fixed version:
from flask import Flask, request
from markupsafe import escape
app = Flask(__name__)
@app.route('/')
def home():
name = request.args.get('name', '')
return f'Hello, {escape(name)}!'
That’s it. One line change, and your app works again.
Alternative Approaches To String Escaping
If you prefer not to use markupsafe, here are other options.
Use Python’s Html Module
Python’s standard library has html.escape:
import html
escaped = html.escape("")
self.assertEqual(result, "<script>alert('xss')</script>")
if __name__ == '__main__':
unittest.main()
Integration Test
Run your full application and check that pages render correctly. Look for any unescaped HTML or new errors.
Conclusion
The "can not import name escape from jinja2" error is a straightforward version mismatch. By importing from markupsafe instead, you can fix it in seconds. Remember to check your Jinja2 version and update your code accordingly.
If you're working on legacy projects, consider upgrading your entire codebase to use markupsafe. It's the recommended approach and ensures compatibility with future Jinja2 releases.
For new projects, always use from markupsafe import escape from the start. This saves you from dealing with this error later.
We hope this guide helped you resolve the issue quickly. If you have further questions, check the official Jinja2 documentation or the markupsafe GitHub repository.