Python Development Mode

Added in version 3.7.

The Python Development Mode introduces additional runtime checks that are too expensive to be enabled by default. It should not be more verbose than the default if the code is correct; new warnings are only emitted when an issue is detected.

It can be enabled using the -X dev command line option or by setting the PYTHONDEVMODE environment variable to 1.

See also Python debug build.

Effects of the Python Development Mode

Enabling the Python Development Mode is similar to the following command, but with additional effects described below:

PYTHONMALLOC=debug PYTHONASYNCIODEBUG=1 python -W default -X faulthandler

Effects of the Python Development Mode:

The Python Development Mode does not enable the tracemalloc module by default, because the overhead cost (to performance and memory) would be too large. Enabling the tracemalloc module provides additional information on the origin of some errors. For example, ResourceWarning logs the traceback where the resource was allocated, and a buffer overflow error logs the traceback where the memory block was allocated.

The Python Development Mode does not prevent the -O command line option from removing assert statements nor from setting __debug__ to False.

The Python Development Mode can only be enabled at the Python startup. Its value can be read from sys.flags.dev_mode.

Changed in version 3.8: The io.IOBase destructor now logs close() exceptions.

Changed in version 3.9: The encoding and errors arguments are now checked for string encoding and decoding operations.

ResourceWarning Example

Example of a script counting the number of lines of the text file specified in the command line:

import sys

def main():
    fp = open(sys.argv[1])
    nlines = len(fp.readlines())
    print(nlines)
    # The file is closed implicitly

if __name__ == "__main__":
    main()

The script does not close the file explicitly. By default, Python does not emit any warning. Example using README.txt, which has 269 lines:

$ python script.py README.txt
269

Enabling the Python Development Mode displays a ResourceWarning warning:

$ python -X dev script.py README.txt
269
script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='README.rst' mode='r' encoding='UTF-8'>
  main()
ResourceWarning: Enable tracemalloc to get the object allocation traceback

In addition, enabling tracemalloc shows the line where the file was opened:

$ python -X dev -X tracemalloc=5 script.py README.rst
269
script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='README.rst' mode='r' encoding='UTF-8'>
  main()
Object allocated at (most recent call last):
  File "script.py", lineno 10
    main()
  File "script.py", lineno 4
    fp = open(sys.argv[1])

The fix is to close explicitly the file. Example using a context manager: