Importerror: cannot import name ‘escape’ from ‘jinja2’ ( Solved )

Importerror cannot import name 'escape' from 'jinja2'

importerror: cannot import name ‘escape’ from ‘jinja2’ error occurs because of restructuring of jinja internal modules in a recent release. In one line if you want to resolve this error, go for the lower version of Jinja module then your existing code will work without any error. On the other side, we can fix this error by keeping the latest version but there we need to import it differently.

In this article, we will practically discuss the easiest way to fix this importerror.

importerror: cannot import name ‘escape’ from ‘jinja2’ ( Solution ) :

As above we discussed, we can solve the problem either way. Let’s start with version fixing and then move the syntax change.

importerror cannot import name 'escape' from 'jinja2' lower down version
importerror cannot import name ‘escape’ from ‘jinja2’ lower down version

Solution 1: Downgrading jinja2 to a lower stable version –

We have observed that we are getting this error on jinja 3.1.0 + version because the escape is now migrated to markupsafe module.  So if you want to keep your code base the same, please lower the version for jinja. It has the same folder path hence the import statement will not through any error.

pip install Jinja2==3.0.3

Here is the release history for jinja2 package. Any of the lower versions to 3.1.0 will work for you.


Solution 2: Changing the import statement –

As I told you that in the latest version, Project structuring is a bit different. Hence we need to align out import statement accordingly. We have to import escape for markupsafe module like the below way-

from markupsafe import escape

Jinja is a really good template development framework and facilitates python-like syntax. That is the main reason behind its popularity. Most of the import error occurs because of such incompatibilities and version mismatch. In most cases, Upgrading the underline package to the latest solves the problem. But that is a bit different here. Hope that helped you in fixing this error.


Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Abhishek ( Chief Editor) , a data scientist with major expertise in NLP and Text Analytics. He has worked on various projects involving text data and have been able to achieve great results. He is currently manages, where he and his team share knowledge and help others learn more about data science.
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner