python error "AttributeError: 'module' object has no attribute 'sha1'"

The problem appeared after installing some brew cask that did some regular cleanup after. Then node-gyp was failing to rebuild some packages for my node application. Reinstalling python 2 helped me.

On macos:

brew reinstall python@2

Cause of the error

When you have a file in the same directory from where you executed the script (or even if it's the script being run itself) named the same as a built-in module, it's loaded instead of the built-in module.

Fix

To fix it you simply need to rename your file hashlib.py to something else and then the Python interpreter will load the built-in module. You may also need to delete the compiled module hashlib.pyc which is located in the same directory as your hashlib.py, otherwise Python will be still loading that module.

Explanation

When you import a module, let's say import hashlib, Python looks for the module hashlib.py in the following locations and in the following order:

  1. directory containing the script being run
  2. built-in modules
  3. directory containing the input script (or the current directory when no file is specified)
  4. PYTHONPATH environment variable (may contain a list of directories)
  5. installation-dependent default path

That means if you execute the script hashlib.py which contains the statement import hashlib, Python imports the script itself instead of built-in module hashlib. In fact, Python compiles your script into the file hashlib.pyc in the same directory and imports that compiled script, so if you just rename hashlib.py and leave haslib.pyc where it is, it will be still loading it. Therefore you also need to delete the haslib.pyc.