A developer names their script `json.py` and tries to use the standard library `json` module. Why does the following code crash?

Python interview question for Advanced practice.

Answer

It raises an AttributeError because Python is importing the local json.py file instead of the standard library module.

Explanation

This is a classic 'shadowing' bug. Because the script itself is named json.py, when it executes import json, Python finds the local file first (due to the current directory being at the start of sys.path). The script then tries to call loads() on itself. Since the local file doesn't have a loads function defined, it raises an AttributeError. Option A is wrong; json is in the standard library. Option C is valid JSON. Option D is false.

Related Questions