brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python -X dev turns on extra runtime checks

Python
~/tips/tip-python-dev-mode-x-dev

python -X dev script.py

Enables extra warnings and checks, such as unclosed files, while a script runs.

Python hides some warnings by default, and an unclosed file is one of them. Development Mode switches them on.

The docs describe -X dev as runtime checks that are too expensive to enable by default. Either of these turns it on, and it can only be set when the interpreter starts:

python -X dev script.py
PYTHONDEVMODE=1 pytest

It shows the DeprecationWarning, ImportWarning, PendingDeprecationWarning and ResourceWarning that are normally hidden. It also installs debug hooks on the memory allocators, calls faulthandler.enable() and turns on asyncio debug mode. Here is a script that opens a file and never closes it:

def main():
    f = open("data.txt")
    f.readline()

main()

A normal run prints nothing. With -X dev you get:

script.py:5: ResourceWarning: unclosed file <_io.TextIOWrapper name='data.txt' mode='r' encoding='UTF-8'>
  main()
ResourceWarning: Enable tracemalloc to get the object allocation traceback

The last line gives a hint. Add -X tracemalloc=5 and Python also shows where the file was opened. The fix is a with open(...) as f: block.

If your code is correct, the docs say Development Mode should not print more than usual, so new output means something to look at. The caveat is cost: the extra checks make the program slower and use more memory, so keep it for development and CI, not production. It was added in Python 3.7.

Further reading: Python Development Mode, Command line and environment

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link