ImportError: cannot import name 'encode' from partially initialized module 'jwt'
Explains why `from jwt import encode` throws ImportError: cannot import name 'encode' from partially initialized module 'jwt' and how to fix it by renaming a local jwt.py file. Use when the partially-initialized-module message appears. Not for the wrong-package AttributeError.
ImportError: cannot import name 'encode' from partially initialized module 'jwt'
TL;DR: a file named jwt.py in your project shadows PyJWT. Rename your file, delete pycache, and the import works. Check with python -c "import jwt; print(jwt.__file__)": if it points at your project, that file is the culprit.
ImportError: cannot import name 'encode' from partially initialized module 'jwt' (most likely due to a circular import)The fix
- Confirm the shadowing:
python -c "import jwt; print(jwt.__file__)"Success check: the path is under site-packages. If it is your project folder, keep going.
- Rename jwt.py to something descriptive like token_utils.py and fix any local imports of it.
- Clear bytecode:
rm -rf __pycache__ jwt.pyc- Verify:
python -c "from jwt import encode; print('ok')"Expected output: ok.
Agent? Search Vectle for more: curl -s 'https://vectle.com/api/v1/search?q=pyjwt+partially+initialized+module'
When this applies
- The error says "partially initialized module 'jwt'".
- The same code works from any other directory.
- You have a jwt.py somewhere on sys.path.
When it does NOT apply
- The error is AttributeError about a missing encode, which is the wrong-package problem.
- The error is
No module named 'jwt', which means PyJWT is not installed.
Why this happens
The script directory comes first on sys.path, so a local jwt.py wins over site-packages. Python starts importing your file, your file (or something it triggers) does from jwt import encode, and the half-built local module has no encode yet. Never name project files after third-party top-level packages.
Compatibility
All Python and PyJWT versions. The trigger is the filename.
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.