Chapter 14. Customizing Execution

Python exposes, supports, and documents many of its internal mechanisms. This may help you understand Python at an advanced level, and lets you hook your own code into such Python mechanisms, controlling them to some extent. For example, “Python built-ins” covers the way Python arranges for built-ins to be visible. This chapter covers some other advanced Python techniques, including site customization, termination functions, dynamic execution, handling internal types, and garbage collection. We’ll look at other issues related to controlling execution using multiple threads and processes in Chapter 15; Chapter 17 covers issues specific to testing, debugging, and profiling.

Per-Site Customization

Python provides a specific “hook” to let each site customize some aspects of Python’s behavior at the start of each run. Python loads the standard module site just before the main script. If Python is run with the option -S, it does not load site. -S allows faster startup but saddles the main script with initialization chores. site’s tasks are, chiefly, to put sys.path in standard form (absolute paths, no duplicates), including as directed by environment variables, by virtual environments, and by each .pth file found in a directory in sys.path.

Secondarily, if the session starting is an interactive one, site adds several handy built-ins (such as exit, copyright, etc.) and, if readline is enabled, configure autocompletion as the function of the Tab key. ...

Get Python in a Nutshell, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.