Blogs / Why a File Named json.py Can Break the Standard Library

Why a File Named json.py Can Break the Standard Library

What a Python.org post says module shadowing is, how a file in your project can take precedence over the standard library and what causes it.

  • Learning
  • 1 min read

For: Learners who write Python scripts and have seen an import error.

What the problem looks like

The issue manifests as seemingly random AttributeError exceptions from modules like json, math, or http for names you know are correct.[1]

What shadowing is and why a project file wins

The issue is usually that a module is “shadowing” the standard library module from a higher-precedence location in sys.path, such as your current working directory or a directory on PYTHONPATH.[1]

There is probably a file named json.py or math.py in your project, and that module takes precedence over the standard library module of the same name, which is only noticed once you start using the module elsewhere in your project.[1]

A file such asjson.py in yourprojectin a higher-precedencelocation on sys.pathThe standard librarymodule of the samenameshadowed, so noticed onlyelsewhere in the projectPython's flat modulenamespaceno delineation betweenstandard library andthird-party modulesshadowscaused by
Why does the project file win?

What causes it

This issue is caused by Python’s flat module namespace; there is no delineation between what is part of the standard library and what are third-party modules, either dependencies or project code.[1]

Sources

  1. One namespace to namespace them all (blog.python.org · checked )

More articles