Debian Codegraph @

Doc/library/sys.rst

raw
1 :mod:`!sys` --- System-specific parameters and functions
2 ========================================================
3
4 .. module:: sys
5 :synopsis: Access system-specific parameters and functions.
6
7 --------------
8
9 This module provides access to some variables used or maintained by the
10 interpreter and to functions that interact strongly with the interpreter. It is
11 always available. Unless explicitly noted otherwise, all variables are read-only.
12
13
14 .. data:: abiflags
15
16 On POSIX systems where Python was built with the standard ``configure``
17 script, this contains the ABI flags as specified by :pep:`3149`.
18
19 .. versionadded:: 3.2
20
21 .. versionchanged:: 3.8
22 Default flags became an empty string (``m`` flag for pymalloc has been
23 removed).
24
25 .. availability:: Unix.
26
27
28 .. function:: addaudithook(hook)
29
30 Append the callable *hook* to the list of active auditing hooks for the
31 current (sub)interpreter.
32
33 When an auditing event is raised through the :func:`sys.audit` function, each
34 hook will be called in the order it was added with the event name and the
35 tuple of arguments. Native hooks added by :c:func:`PySys_AddAuditHook` are
36 called first, followed by hooks added in the current (sub)interpreter. Hooks
37 can then log the event, raise an exception to abort the operation,
38 or terminate the process entirely.
39
40 Note that audit hooks are primarily for collecting information about internal
41 or otherwise unobservable actions, whether by Python or libraries written in
42 Python. They are not suitable for implementing a "sandbox". In particular,
43 malicious code can trivially disable or bypass hooks added using this
44 function. At a minimum, any security-sensitive hooks must be added using the
45 C API :c:func:`PySys_AddAuditHook` before initialising the runtime, and any
46 modules allowing arbitrary memory modification (such as :mod:`ctypes`) should
47 be completely removed or closely monitored.
48
49 .. audit-event:: sys.addaudithook "" sys.addaudithook
50
51 Calling :func:`sys.addaudithook` will itself raise an auditing event
52 named ``sys.addaudithook`` with no arguments. If any
53 existing hooks raise an exception derived from :class:`RuntimeError`, the
54 new hook will not be added and the exception suppressed. As a result,
55 callers cannot assume that their hook has been added unless they control
56 all existing hooks.
57
58 See the :ref:`audit events table <audit-events>` for all events raised by
59 CPython, and :pep:`578` for the original design discussion.
60
61 .. versionadded:: 3.8
62
63 .. versionchanged:: 3.8.1
64
65 Exceptions derived from :class:`Exception` but not :class:`RuntimeError`
66 are no longer suppressed.
67
68 .. impl-detail::
69
70 When tracing is enabled (see :func:`settrace`), Python hooks are only
71 traced if the callable has a ``__cantrace__`` member that is set to a
72 true value. Otherwise, trace functions will skip the hook.
73
74
75 .. data:: argv
76
77 The list of command line arguments passed to a Python script. ``argv[0]`` is the
78 script name (it is operating system dependent whether this is a full pathname or
79 not). If the command was executed using the :option:`-c` command line option to
80 the interpreter, ``argv[0]`` is set to the string ``'-c'``. If no script name
81 was passed to the Python interpreter, ``argv[0]`` is the empty string.
82
83 To loop over the standard input, or the list of files given on the
84 command line, see the :mod:`fileinput` module.
85
86 See also :data:`sys.orig_argv`.
87
88 .. note::
89 On Unix, command line arguments are passed by bytes from OS. Python decodes
90 them with filesystem encoding and "surrogateescape" error handler.
91 When you need original bytes, you can get it by
92 ``[os.fsencode(arg) for arg in sys.argv]``.
93
94
95 .. _auditing:
96
97 .. function:: audit(event, *args)
98
99 .. index:: single: auditing
100
101 Raise an auditing event and trigger any active auditing hooks.
102 *event* is a string identifying the event, and *args* may contain
103 optional arguments with more information about the event. The
104 number and types of arguments for a given event are considered a
105 public and stable API and should not be modified between releases.
106
107 For example, one auditing event is named ``os.chdir``. This event has
108 one argument called *path* that will contain the requested new
109 working directory.
110
111 :func:`sys.audit` will call the existing auditing hooks, passing
112 the event name and arguments, and will re-raise the first exception
113 from any hook. In general, if an exception is raised, it should not
114 be handled and the process should be terminated as quickly as
115 possible. This allows hook implementations to decide how to respond
116 to particular events: they can merely log the event or abort the
117 operation by raising an exception.
118
119 Hooks are added using the :func:`sys.addaudithook` or
120 :c:func:`PySys_AddAuditHook` functions.
121
122 The native equivalent of this function is :c:func:`PySys_Audit`. Using the
123 native function is preferred when possible.
124
125 See the :ref:`audit events table <audit-events>` for all events raised by
126 CPython.
127
128 .. versionadded:: 3.8
129
130
131 .. data:: base_exec_prefix
132
133 Set during Python startup, before ``site.py`` is run, to the same value as
134 :data:`exec_prefix`. If not running in a
135 :ref:`virtual environment <venv-def>`, the values will stay the same; if
136 ``site.py`` finds that a virtual environment is in use, the values of
137 :data:`prefix` and :data:`exec_prefix` will be changed to point to the
138 virtual environment, whereas :data:`base_prefix` and
139 :data:`base_exec_prefix` will remain pointing to the base Python
140 installation (the one which the virtual environment was created from).
141
142 .. versionadded:: 3.3
143
144
145 .. data:: base_prefix
146
147 Set during Python startup, before ``site.py`` is run, to the same value as
148 :data:`prefix`. If not running in a :ref:`virtual environment <venv-def>`, the values
149 will stay the same; if ``site.py`` finds that a virtual environment is in
150 use, the values of :data:`prefix` and :data:`exec_prefix` will be changed to
151 point to the virtual environment, whereas :data:`base_prefix` and
152 :data:`base_exec_prefix` will remain pointing to the base Python
153 installation (the one which the virtual environment was created from).
154
155 .. versionadded:: 3.3
156
157
158 .. data:: byteorder
159
160 An indicator of the native byte order. This will have the value ``'big'`` on
161 big-endian (most-significant byte first) platforms, and ``'little'`` on
162 little-endian (least-significant byte first) platforms.
163
164
165 .. data:: builtin_module_names
166
167 A tuple of strings containing the names of all modules that are compiled into this
168 Python interpreter. (This information is not available in any other way ---
169 ``modules.keys()`` only lists the imported modules.)
170
171 See also the :data:`sys.stdlib_module_names` list.
172
173
174 .. function:: call_tracing(func, args)
175
176 Call ``func(*args)``, while tracing is enabled. The tracing state is saved,
177 and restored afterwards. This is intended to be called from a debugger from
178 a checkpoint, to recursively debug or profile some other code.
179
180 Tracing is suspended while calling a tracing function set by
181 :func:`settrace` or :func:`setprofile` to avoid infinite recursion.
182 :func:`!call_tracing` enables explicit recursion of the tracing function.
183
184
185 .. data:: copyright
186
187 A string containing the copyright pertaining to the Python interpreter.
188
189
190 .. function:: _clear_type_cache()
191
192 Clear the internal type cache. The type cache is used to speed up attribute
193 and method lookups. Use the function *only* to drop unnecessary references
194 during reference leak debugging.
195
196 This function should be used for internal and specialized purposes only.
197
198 .. deprecated:: 3.13
199 Use the more general :func:`_clear_internal_caches` function instead.
200
201
202 .. function:: _clear_internal_caches()
203
204 Clear all internal performance-related caches. Use this function *only* to
205 release unnecessary references and memory blocks when hunting for leaks.
206
207 .. versionadded:: 3.13
208
209
210 .. function:: _current_frames()
211
212 Return a dictionary mapping each thread's identifier to the topmost stack frame
213 currently active in that thread at the time the function is called. Note that
214 functions in the :mod:`traceback` module can build the call stack given such a
215 frame.
216
217 This is most useful for debugging deadlock: this function does not require the
218 deadlocked threads' cooperation, and such threads' call stacks are frozen for as
219 long as they remain deadlocked. The frame returned for a non-deadlocked thread
220 may bear no relationship to that thread's current activity by the time calling
221 code examines the frame.
222
223 This function should be used for internal and specialized purposes only.
224
225 .. audit-event:: sys._current_frames "" sys._current_frames
226
227 .. function:: _current_exceptions()
228
229 Return a dictionary mapping each thread's identifier to the topmost exception
230 currently active in that thread at the time the function is called.
231 If a thread is not currently handling an exception, it is not included in
232 the result dictionary.
233
234 This is most useful for statistical profiling.
235
236 This function should be used for internal and specialized purposes only.
237
238 .. audit-event:: sys._current_exceptions "" sys._current_exceptions
239
240 .. versionchanged:: 3.12
241 Each value in the dictionary is now a single exception instance, rather
242 than a 3-tuple as returned from ``sys.exc_info()``.
243
244 .. function:: breakpointhook()
245
246 This hook function is called by built-in :func:`breakpoint`. By default,
247 it drops you into the :mod:`pdb` debugger, but it can be set to any other
248 function so that you can choose which debugger gets used.
249
250 The signature of this function is dependent on what it calls. For example,
251 the default binding (e.g. ``pdb.set_trace()``) expects no arguments, but
252 you might bind it to a function that expects additional arguments
253 (positional and/or keyword). The built-in ``breakpoint()`` function passes
254 its ``*args`` and ``**kws`` straight through. Whatever
255 ``breakpointhooks()`` returns is returned from ``breakpoint()``.
256
257 The default implementation first consults the environment variable
258 :envvar:`PYTHONBREAKPOINT`. If that is set to ``"0"`` then this function
259 returns immediately; i.e. it is a no-op. If the environment variable is
260 not set, or is set to the empty string, ``pdb.set_trace()`` is called.
261 Otherwise this variable should name a function to run, using Python's
262 dotted-import nomenclature, e.g. ``package.subpackage.module.function``.
263 In this case, ``package.subpackage.module`` would be imported and the
264 resulting module must have a callable named ``function()``. This is run,
265 passing in ``*args`` and ``**kws``, and whatever ``function()`` returns,
266 ``sys.breakpointhook()`` returns to the built-in :func:`breakpoint`
267 function.
268
269 Note that if anything goes wrong while importing the callable named by
270 :envvar:`PYTHONBREAKPOINT`, a :exc:`RuntimeWarning` is reported and the
271 breakpoint is ignored.
272
273 Also note that if ``sys.breakpointhook()`` is overridden programmatically,
274 :envvar:`PYTHONBREAKPOINT` is *not* consulted.
275
276 .. versionadded:: 3.7
277
278 .. function:: _debugmallocstats()
279
280 Print low-level information to stderr about the state of CPython's memory
281 allocator.
282
283 If Python is :ref:`built in debug mode <debug-build>` (:option:`configure
284 --with-pydebug option <--with-pydebug>`), it also performs some expensive
285 internal consistency checks.
286
287 .. versionadded:: 3.3
288
289 .. impl-detail::
290
291 This function is specific to CPython. The exact output format is not
292 defined here, and may change.
293
294
295 .. data:: dllhandle
296
297 Integer specifying the handle of the Python DLL.
298
299 .. availability:: Windows.
300
301
302 .. function:: displayhook(value)
303
304 If *value* is not ``None``, this function prints ``repr(value)`` to
305 ``sys.stdout``, and saves *value* in ``builtins._``. If ``repr(value)`` is
306 not encodable to ``sys.stdout.encoding`` with ``sys.stdout.errors`` error
307 handler (which is probably ``'strict'``), encode it to
308 ``sys.stdout.encoding`` with ``'backslashreplace'`` error handler.
309
310 ``sys.displayhook`` is called on the result of evaluating an :term:`expression`
311 entered in an interactive Python session. The display of these values can be
312 customized by assigning another one-argument function to ``sys.displayhook``.
313
314 Pseudo-code::
315
316 def displayhook(value):
317 if value is None:
318 return
319 # Set '_' to None to avoid recursion
320 builtins._ = None
321 text = repr(value)
322 try:
323 sys.stdout.write(text)
324 except UnicodeEncodeError:
325 bytes = text.encode(sys.stdout.encoding, 'backslashreplace')
326 if hasattr(sys.stdout, 'buffer'):
327 sys.stdout.buffer.write(bytes)
328 else:
329 text = bytes.decode(sys.stdout.encoding, 'strict')
330 sys.stdout.write(text)
331 sys.stdout.write("\n")
332 builtins._ = value
333
334 .. versionchanged:: 3.2
335 Use ``'backslashreplace'`` error handler on :exc:`UnicodeEncodeError`.
336
337
338 .. data:: dont_write_bytecode
339
340 If this is true, Python won't try to write ``.pyc`` files on the
341 import of source modules. This value is initially set to ``True`` or
342 ``False`` depending on the :option:`-B` command line option and the
343 :envvar:`PYTHONDONTWRITEBYTECODE` environment variable, but you can set it
344 yourself to control bytecode file generation.
345
346
347 .. data:: _emscripten_info
348
349 A :term:`named tuple` holding information about the environment on the
350 *wasm32-emscripten* platform. The named tuple is provisional and may change
351 in the future.
352
353 .. attribute:: _emscripten_info.emscripten_version
354
355 Emscripten version as tuple of ints (major, minor, micro), e.g. ``(3, 1, 8)``.
356
357 .. attribute:: _emscripten_info.runtime
358
359 Runtime string, e.g. browser user agent, ``'Node.js v14.18.2'``, or ``'UNKNOWN'``.
360
361 .. attribute:: _emscripten_info.pthreads
362
363 ``True`` if Python is compiled with Emscripten pthreads support.
364
365 .. attribute:: _emscripten_info.shared_memory
366
367 ``True`` if Python is compiled with shared memory support.
368
369 .. availability:: Emscripten.
370
371 .. versionadded:: 3.11
372
373
374 .. data:: pycache_prefix
375
376 If this is set (not ``None``), Python will write bytecode-cache ``.pyc``
377 files to (and read them from) a parallel directory tree rooted at this
378 directory, rather than from ``__pycache__`` directories in the source code
379 tree. Any ``__pycache__`` directories in the source code tree will be ignored
380 and new ``.pyc`` files written within the pycache prefix. Thus if you use
381 :mod:`compileall` as a pre-build step, you must ensure you run it with the
382 same pycache prefix (if any) that you will use at runtime.
383
384 A relative path is interpreted relative to the current working directory.
385
386 This value is initially set based on the value of the :option:`-X`
387 ``pycache_prefix=PATH`` command-line option or the
388 :envvar:`PYTHONPYCACHEPREFIX` environment variable (command-line takes
389 precedence). If neither are set, it is ``None``.
390
391 .. versionadded:: 3.8
392
393
394 .. function:: excepthook(type, value, traceback)
395
396 This function prints out a given traceback and exception to ``sys.stderr``.
397
398 When an exception other than :exc:`SystemExit` is raised and uncaught, the interpreter calls
399 ``sys.excepthook`` with three arguments, the exception class, exception
400 instance, and a traceback object. In an interactive session this happens just
401 before control is returned to the prompt; in a Python program this happens just
402 before the program exits. The handling of such top-level exceptions can be
403 customized by assigning another three-argument function to ``sys.excepthook``.
404
405 .. audit-event:: sys.excepthook hook,type,value,traceback sys.excepthook
406
407 Raise an auditing event ``sys.excepthook`` with arguments ``hook``,
408 ``type``, ``value``, ``traceback`` when an uncaught exception occurs.
409 If no hook has been set, ``hook`` may be ``None``. If any hook raises
410 an exception derived from :class:`RuntimeError` the call to the hook will
411 be suppressed. Otherwise, the audit hook exception will be reported as
412 unraisable and ``sys.excepthook`` will be called.
413
414 .. seealso::
415
416 The :func:`sys.unraisablehook` function handles unraisable exceptions
417 and the :func:`threading.excepthook` function handles exception raised
418 by :func:`threading.Thread.run`.
419
420
421 .. data:: __breakpointhook__
422 __displayhook__
423 __excepthook__
424 __unraisablehook__
425
426 These objects contain the original values of ``breakpointhook``,
427 ``displayhook``, ``excepthook``, and ``unraisablehook`` at the start of the
428 program. They are saved so that ``breakpointhook``, ``displayhook`` and
429 ``excepthook``, ``unraisablehook`` can be restored in case they happen to
430 get replaced with broken or alternative objects.
431
432 .. versionadded:: 3.7
433 __breakpointhook__
434
435 .. versionadded:: 3.8
436 __unraisablehook__
437
438
439 .. function:: exception()
440
441 This function, when called while an exception handler is executing (such as
442 an ``except`` or ``except*`` clause), returns the exception instance that
443 was caught by this handler. When exception handlers are nested within one
444 another, only the exception handled by the innermost handler is accessible.
445
446 If no exception handler is executing, this function returns ``None``.
447
448 .. versionadded:: 3.11
449
450
451 .. function:: exc_info()
452
453 This function returns the old-style representation of the handled
454 exception. If an exception ``e`` is currently handled (so
455 :func:`exception` would return ``e``), :func:`exc_info` returns the
456 tuple ``(type(e), e, e.__traceback__)``.
457 That is, a tuple containing the type of the exception (a subclass of
458 :exc:`BaseException`), the exception itself, and a :ref:`traceback
459 object <traceback-objects>` which typically encapsulates the call
460 stack at the point where the exception last occurred.
461
462 .. index:: pair: object; traceback
463
464 If no exception is being handled anywhere on the stack, this function
465 return a tuple containing three ``None`` values.
466
467 .. versionchanged:: 3.11
468 The ``type`` and ``traceback`` fields are now derived from the ``value``
469 (the exception instance), so when an exception is modified while it is
470 being handled, the changes are reflected in the results of subsequent
471 calls to :func:`exc_info`.
472
473 .. data:: exec_prefix
474
475 A string giving the site-specific directory prefix where the platform-dependent
476 Python files are installed; by default, this is also ``'/usr/local'``. This can
477 be set at build time with the ``--exec-prefix`` argument to the
478 :program:`configure` script. Specifically, all configuration files (e.g. the
479 :file:`pyconfig.h` header file) are installed in the directory
480 :file:`{exec_prefix}/lib/python{X.Y}/config`, and shared library modules are
481 installed in :file:`{exec_prefix}/lib/python{X.Y}/lib-dynload`, where *X.Y*
482 is the version number of Python, for example ``3.2``.
483
484 .. note::
485
486 If a :ref:`virtual environment <venv-def>` is in effect, this
487 value will be changed in ``site.py`` to point to the virtual environment.
488 The value for the Python installation will still be available, via
489 :data:`base_exec_prefix`.
490
491
492 .. data:: executable
493
494 A string giving the absolute path of the executable binary for the Python
495 interpreter, on systems where this makes sense. If Python is unable to retrieve
496 the real path to its executable, :data:`sys.executable` will be an empty string
497 or ``None``.
498
499
500 .. function:: exit([arg])
501
502 Raise a :exc:`SystemExit` exception, signaling an intention to exit the interpreter.
503
504 The optional argument *arg* can be an integer giving the exit status
505 (defaulting to zero), or another type of object. If it is an integer, zero
506 is considered "successful termination" and any nonzero value is considered
507 "abnormal termination" by shells and the like. Most systems require it to be
508 in the range 0--127, and produce undefined results otherwise. Some systems
509 have a convention for assigning specific meanings to specific exit codes, but
510 these are generally underdeveloped; Unix programs generally use 2 for command
511 line syntax errors and 1 for all other kinds of errors. If another type of
512 object is passed, ``None`` is equivalent to passing zero, and any other
513 object is printed to :data:`stderr` and results in an exit code of 1. In
514 particular, ``sys.exit("some error message")`` is a quick way to exit a
515 program when an error occurs.
516
517 Since :func:`exit` ultimately "only" raises an exception, it will only exit
518 the process when called from the main thread, and the exception is not
519 intercepted. Cleanup actions specified by finally clauses of :keyword:`try` statements
520 are honored, and it is possible to intercept the exit attempt at an outer level.
521
522 .. versionchanged:: 3.6
523 If an error occurs in the cleanup after the Python interpreter
524 has caught :exc:`SystemExit` (such as an error flushing buffered data
525 in the standard streams), the exit status is changed to 120.
526
527
528 .. data:: flags
529
530 The :term:`named tuple` *flags* exposes the status of command line
531 flags. The attributes are read only.
532
533 .. list-table::
534
535 * - .. attribute:: flags.debug
536 - :option:`-d`
537
538 * - .. attribute:: flags.inspect
539 - :option:`-i`
540
541 * - .. attribute:: flags.interactive
542 - :option:`-i`
543
544 * - .. attribute:: flags.isolated
545 - :option:`-I`
546
547 * - .. attribute:: flags.optimize
548 - :option:`-O` or :option:`-OO`
549
550 * - .. attribute:: flags.dont_write_bytecode
551 - :option:`-B`
552
553 * - .. attribute:: flags.no_user_site
554 - :option:`-s`
555
556 * - .. attribute:: flags.no_site
557 - :option:`-S`
558
559 * - .. attribute:: flags.ignore_environment
560 - :option:`-E`
561
562 * - .. attribute:: flags.verbose
563 - :option:`-v`
564
565 * - .. attribute:: flags.bytes_warning
566 - :option:`-b`
567
568 * - .. attribute:: flags.quiet
569 - :option:`-q`
570
571 * - .. attribute:: flags.hash_randomization
572 - :option:`-R`
573
574 * - .. attribute:: flags.dev_mode
575 - :option:`-X dev <-X>` (:ref:`Python Development Mode <devmode>`)
576
577 * - .. attribute:: flags.utf8_mode
578 - :option:`-X utf8 <-X>`
579
580 * - .. attribute:: flags.safe_path
581 - :option:`-P`
582
583 * - .. attribute:: flags.int_max_str_digits
584 - :option:`-X int_max_str_digits <-X>`
585 (:ref:`integer string conversion length limitation <int_max_str_digits>`)
586
587 * - .. attribute:: flags.warn_default_encoding
588 - :option:`-X warn_default_encoding <-X>`
589
590 .. versionchanged:: 3.2
591 Added ``quiet`` attribute for the new :option:`-q` flag.
592
593 .. versionadded:: 3.2.3
594 The ``hash_randomization`` attribute.
595
596 .. versionchanged:: 3.3
597 Removed obsolete ``division_warning`` attribute.
598
599 .. versionchanged:: 3.4
600 Added ``isolated`` attribute for :option:`-I` ``isolated`` flag.
601
602 .. versionchanged:: 3.7
603 Added the ``dev_mode`` attribute for the new :ref:`Python Development
604 Mode <devmode>` and the ``utf8_mode`` attribute for the new :option:`-X`
605 ``utf8`` flag.
606
607 .. versionchanged:: 3.10
608 Added ``warn_default_encoding`` attribute for :option:`-X` ``warn_default_encoding`` flag.
609
610 .. versionchanged:: 3.11
611 Added the ``safe_path`` attribute for :option:`-P` option.
612
613 .. versionchanged:: 3.11
614 Added the ``int_max_str_digits`` attribute.
615
616
617 .. data:: float_info
618
619 A :term:`named tuple` holding information about the float type. It
620 contains low level information about the precision and internal
621 representation. The values correspond to the various floating-point
622 constants defined in the standard header file :file:`float.h` for the 'C'
623 programming language; see section 5.2.4.2.2 of the 1999 ISO/IEC C standard
624 [C99]_, 'Characteristics of floating types', for details.
625
626 .. list-table:: Attributes of the :data:`!float_info` :term:`named tuple`
627 :header-rows: 1
628
629 * - attribute
630 - float.h macro
631 - explanation
632
633 * - .. attribute:: float_info.epsilon
634 - :c:macro:`!DBL_EPSILON`
635 - difference between 1.0 and the least value greater than 1.0 that is
636 representable as a float.
637
638 See also :func:`math.ulp`.
639
640 * - .. attribute:: float_info.dig
641 - :c:macro:`!DBL_DIG`
642 - The maximum number of decimal digits that can be faithfully
643 represented in a float; see below.
644
645 * - .. attribute:: float_info.mant_dig
646 - :c:macro:`!DBL_MANT_DIG`
647 - Float precision: the number of base-``radix`` digits in the
648 significand of a float.
649
650 * - .. attribute:: float_info.max
651 - :c:macro:`!DBL_MAX`
652 - The maximum representable positive finite float.
653
654 * - .. attribute:: float_info.max_exp
655 - :c:macro:`!DBL_MAX_EXP`
656 - The maximum integer *e* such that ``radix**(e-1)`` is a representable
657 finite float.
658
659 * - .. attribute:: float_info.max_10_exp
660 - :c:macro:`!DBL_MAX_10_EXP`
661 - The maximum integer *e* such that ``10**e`` is in the range of
662 representable finite floats.
663
664 * - .. attribute:: float_info.min
665 - :c:macro:`!DBL_MIN`
666 - The minimum representable positive *normalized* float.
667
668 Use :func:`math.ulp(0.0) <math.ulp>` to get the smallest positive
669 *denormalized* representable float.
670
671 * - .. attribute:: float_info.min_exp
672 - :c:macro:`!DBL_MIN_EXP`
673 - The minimum integer *e* such that ``radix**(e-1)`` is a normalized
674 float.
675
676 * - .. attribute:: float_info.min_10_exp
677 - :c:macro:`!DBL_MIN_10_EXP`
678 - The minimum integer *e* such that ``10**e`` is a normalized float.
679
680 * - .. attribute:: float_info.radix
681 - :c:macro:`!FLT_RADIX`
682 - The radix of exponent representation.
683
684 * - .. attribute:: float_info.rounds
685 - :c:macro:`!FLT_ROUNDS`
686 - An integer representing the rounding mode for floating-point arithmetic.
687 This reflects the value of the system :c:macro:`!FLT_ROUNDS` macro
688 at interpreter startup time:
689
690 * ``-1``: indeterminable
691 * ``0``: toward zero
692 * ``1``: to nearest
693 * ``2``: toward positive infinity
694 * ``3``: toward negative infinity
695
696 All other values for :c:macro:`!FLT_ROUNDS` characterize
697 implementation-defined rounding behavior.
698
699 The attribute :attr:`sys.float_info.dig` needs further explanation. If
700 ``s`` is any string representing a decimal number with at most
701 :attr:`!sys.float_info.dig` significant digits, then converting ``s`` to a
702 float and back again will recover a string representing the same decimal
703 value::
704
705 >>> import sys
706 >>> sys.float_info.dig
707 15
708 >>> s = '3.14159265358979' # decimal string with 15 significant digits
709 >>> format(float(s), '.15g') # convert to float and back -> same value
710 '3.14159265358979'
711
712 But for strings with more than :attr:`sys.float_info.dig` significant digits,
713 this isn't always true::
714
715 >>> s = '9876543211234567' # 16 significant digits is too many!
716 >>> format(float(s), '.16g') # conversion changes value
717 '9876543211234568'
718
719 .. data:: float_repr_style
720
721 A string indicating how the :func:`repr` function behaves for
722 floats. If the string has value ``'short'`` then for a finite
723 float ``x``, ``repr(x)`` aims to produce a short string with the
724 property that ``float(repr(x)) == x``. This is the usual behaviour
725 in Python 3.1 and later. Otherwise, ``float_repr_style`` has value
726 ``'legacy'`` and ``repr(x)`` behaves in the same way as it did in
727 versions of Python prior to 3.1.
728
729 .. versionadded:: 3.1
730
731
732 .. function:: getallocatedblocks()
733
734 Return the number of memory blocks currently allocated by the interpreter,
735 regardless of their size. This function is mainly useful for tracking
736 and debugging memory leaks. Because of the interpreter's internal
737 caches, the result can vary from call to call; you may have to call
738 :func:`_clear_internal_caches` and :func:`gc.collect` to get more
739 predictable results.
740
741 If a Python build or implementation cannot reasonably compute this
742 information, :func:`getallocatedblocks` is allowed to return 0 instead.
743
744 .. versionadded:: 3.4
745
746
747 .. function:: getunicodeinternedsize()
748
749 Return the number of unicode objects that have been interned.
750
751 .. versionadded:: 3.12
752
753
754 .. function:: getandroidapilevel()
755
756 Return the build-time API level of Android as an integer. This represents the
757 minimum version of Android this build of Python can run on. For runtime
758 version information, see :func:`platform.android_ver`.
759
760 .. availability:: Android.
761
762 .. versionadded:: 3.7
763
764
765 .. function:: getdefaultencoding()
766
767 Return ``'utf-8'``. This is the name of the default string encoding, used
768 in methods like :meth:`str.encode`.
769
770
771 .. function:: getdlopenflags()
772
773 Return the current value of the flags that are used for
774 :c:func:`dlopen` calls. Symbolic names for the flag values can be
775 found in the :mod:`os` module (:samp:`RTLD_{xxx}` constants, e.g.
776 :const:`os.RTLD_LAZY`).
777
778 .. availability:: Unix.
779
780
781 .. function:: getfilesystemencoding()
782
783 Get the :term:`filesystem encoding <filesystem encoding and error handler>`:
784 the encoding used with the :term:`filesystem error handler <filesystem
785 encoding and error handler>` to convert between Unicode filenames and bytes
786 filenames. The filesystem error handler is returned from
787 :func:`getfilesystemencodeerrors`.
788
789 For best compatibility, str should be used for filenames in all cases,
790 although representing filenames as bytes is also supported. Functions
791 accepting or returning filenames should support either str or bytes and
792 internally convert to the system's preferred representation.
793
794 :func:`os.fsencode` and :func:`os.fsdecode` should be used to ensure that
795 the correct encoding and errors mode are used.
796
797 The :term:`filesystem encoding and error handler` are configured at Python
798 startup by the :c:func:`PyConfig_Read` function: see
799 :c:member:`~PyConfig.filesystem_encoding` and
800 :c:member:`~PyConfig.filesystem_errors` members of :c:type:`PyConfig`.
801
802 .. versionchanged:: 3.2
803 :func:`getfilesystemencoding` result cannot be ``None`` anymore.
804
805 .. versionchanged:: 3.6
806 Windows is no longer guaranteed to return ``'mbcs'``. See :pep:`529`
807 and :func:`_enablelegacywindowsfsencoding` for more information.
808
809 .. versionchanged:: 3.7
810 Return ``'utf-8'`` if the :ref:`Python UTF-8 Mode <utf8-mode>` is
811 enabled.
812
813
814 .. function:: getfilesystemencodeerrors()
815
816 Get the :term:`filesystem error handler <filesystem encoding and error
817 handler>`: the error handler used with the :term:`filesystem encoding
818 <filesystem encoding and error handler>` to convert between Unicode
819 filenames and bytes filenames. The filesystem encoding is returned from
820 :func:`getfilesystemencoding`.
821
822 :func:`os.fsencode` and :func:`os.fsdecode` should be used to ensure that
823 the correct encoding and errors mode are used.
824
825 The :term:`filesystem encoding and error handler` are configured at Python
826 startup by the :c:func:`PyConfig_Read` function: see
827 :c:member:`~PyConfig.filesystem_encoding` and
828 :c:member:`~PyConfig.filesystem_errors` members of :c:type:`PyConfig`.
829
830 .. versionadded:: 3.6
831
832 .. function:: get_int_max_str_digits()
833
834 Returns the current value for the :ref:`integer string conversion length
835 limitation <int_max_str_digits>`. See also :func:`set_int_max_str_digits`.
836
837 .. versionadded:: 3.11
838
839 .. function:: getrefcount(object)
840
841 Return the reference count of the *object*. The count returned is generally one
842 higher than you might expect, because it includes the (temporary) reference as
843 an argument to :func:`getrefcount`.
844
845 Note that the returned value may not actually reflect how many
846 references to the object are actually held. For example, some
847 objects are :term:`immortal` and have a very high refcount that does not
848 reflect the actual number of references. Consequently, do not rely
849 on the returned value to be accurate, other than a value of 0 or 1.
850
851 .. versionchanged:: 3.12
852 Immortal objects have very large refcounts that do not match
853 the actual number of references to the object.
854
855 .. function:: getrecursionlimit()
856
857 Return the current value of the recursion limit, the maximum depth of the Python
858 interpreter stack. This limit prevents infinite recursion from causing an
859 overflow of the C stack and crashing Python. It can be set by
860 :func:`setrecursionlimit`.
861
862
863 .. function:: getsizeof(object[, default])
864
865 Return the size of an object in bytes. The object can be any type of
866 object. All built-in objects will return correct results, but this
867 does not have to hold true for third-party extensions as it is implementation
868 specific.
869
870 Only the memory consumption directly attributed to the object is
871 accounted for, not the memory consumption of objects it refers to.
872
873 If given, *default* will be returned if the object does not provide means to
874 retrieve the size. Otherwise a :exc:`TypeError` will be raised.
875
876 :func:`getsizeof` calls the object's ``__sizeof__`` method and adds an
877 additional garbage collector overhead if the object is managed by the garbage
878 collector.
879
880 See `recursive sizeof recipe <https://code.activestate.com/recipes/577504-compute-memory-footprint-of-an-object-and-its-cont/>`_
881 for an example of using :func:`getsizeof` recursively to find the size of
882 containers and all their contents.
883
884 .. function:: getswitchinterval()
885
886 Return the interpreter's "thread switch interval" in seconds; see
887 :func:`setswitchinterval`.
888
889 .. versionadded:: 3.2
890
891
892 .. function:: _getframe([depth])
893
894 Return a frame object from the call stack. If optional integer *depth* is
895 given, return the frame object that many calls below the top of the stack. If
896 that is deeper than the call stack, :exc:`ValueError` is raised. The default
897 for *depth* is zero, returning the frame at the top of the call stack.
898
899 .. audit-event:: sys._getframe frame sys._getframe
900
901 .. impl-detail::
902
903 This function should be used for internal and specialized purposes only.
904 It is not guaranteed to exist in all implementations of Python.
905
906
907 .. function:: _getframemodulename([depth])
908
909 Return the name of a module from the call stack. If optional integer *depth*
910 is given, return the module that many calls below the top of the stack. If
911 that is deeper than the call stack, or if the module is unidentifiable,
912 ``None`` is returned. The default for *depth* is zero, returning the
913 module at the top of the call stack.
914
915 .. audit-event:: sys._getframemodulename depth sys._getframemodulename
916
917 .. impl-detail::
918
919 This function should be used for internal and specialized purposes only.
920 It is not guaranteed to exist in all implementations of Python.
921
922 .. versionadded:: 3.12
923
924
925 .. function:: getobjects(limit[, type])
926
927 This function only exists if CPython was built using the
928 specialized configure option :option:`--with-trace-refs`.
929 It is intended only for debugging garbage-collection issues.
930
931 Return a list of up to *limit* dynamically allocated Python objects.
932 If *type* is given, only objects of that exact type (not subtypes)
933 are included.
934
935 Objects from the list are not safe to use.
936 Specifically, the result will include objects from all interpreters that
937 share their object allocator state (that is, ones created with
938 :c:member:`PyInterpreterConfig.use_main_obmalloc` set to 1
939 or using :c:func:`Py_NewInterpreter`, and the
940 :ref:`main interpreter <sub-interpreter-support>`).
941 Mixing objects from different interpreters may lead to crashes
942 or other unexpected behavior.
943
944 .. impl-detail::
945
946 This function should be used for specialized purposes only.
947 It is not guaranteed to exist in all implementations of Python.
948
949 .. versionchanged:: 3.13.1
950
951 The result may include objects from other interpreters.
952
953
954 .. function:: getprofile()
955
956 .. index::
957 single: profile function
958 single: profiler
959
960 Get the profiler function as set by :func:`setprofile`.
961
962
963 .. function:: gettrace()
964
965 .. index::
966 single: trace function
967 single: debugger
968
969 Get the trace function as set by :func:`settrace`.
970
971 .. impl-detail::
972
973 The :func:`gettrace` function is intended only for implementing debuggers,
974 profilers, coverage tools and the like. Its behavior is part of the
975 implementation platform, rather than part of the language definition, and
976 thus may not be available in all Python implementations.
977
978
979 .. function:: getwindowsversion()
980
981 Return a named tuple describing the Windows version
982 currently running. The named elements are *major*, *minor*,
983 *build*, *platform*, *service_pack*, *service_pack_minor*,
984 *service_pack_major*, *suite_mask*, *product_type* and
985 *platform_version*. *service_pack* contains a string,
986 *platform_version* a 3-tuple and all other values are
987 integers. The components can also be accessed by name, so
988 ``sys.getwindowsversion()[0]`` is equivalent to
989 ``sys.getwindowsversion().major``. For compatibility with prior
990 versions, only the first 5 elements are retrievable by indexing.
991
992 *platform* will be ``2`` (VER_PLATFORM_WIN32_NT).
993
994 *product_type* may be one of the following values:
995
996 +---------------------------------------+---------------------------------+
997 | Constant | Meaning |
998 +=======================================+=================================+
999 | ``1`` (VER_NT_WORKSTATION) | The system is a workstation. |
1000 +---------------------------------------+---------------------------------+
1001 | ``2`` (VER_NT_DOMAIN_CONTROLLER) | The system is a domain |
1002 | | controller. |
1003 +---------------------------------------+---------------------------------+
1004 | ``3`` (VER_NT_SERVER) | The system is a server, but not |
1005 | | a domain controller. |
1006 +---------------------------------------+---------------------------------+
1007
1008 This function wraps the Win32 :c:func:`!GetVersionEx` function; see the
1009 Microsoft documentation on :c:func:`!OSVERSIONINFOEX` for more information
1010 about these fields.
1011
1012 *platform_version* returns the major version, minor version and
1013 build number of the current operating system, rather than the version that
1014 is being emulated for the process. It is intended for use in logging rather
1015 than for feature detection.
1016
1017 .. note::
1018 *platform_version* derives the version from kernel32.dll which can be of a different
1019 version than the OS version. Please use :mod:`platform` module for achieving accurate
1020 OS version.
1021
1022 .. availability:: Windows.
1023
1024 .. versionchanged:: 3.2
1025 Changed to a named tuple and added *service_pack_minor*,
1026 *service_pack_major*, *suite_mask*, and *product_type*.
1027
1028 .. versionchanged:: 3.6
1029 Added *platform_version*
1030
1031
1032 .. function:: get_asyncgen_hooks()
1033
1034 Returns an *asyncgen_hooks* object, which is similar to a
1035 :class:`~collections.namedtuple` of the form ``(firstiter, finalizer)``,
1036 where *firstiter* and *finalizer* are expected to be either ``None`` or
1037 functions which take an :term:`asynchronous generator iterator` as an
1038 argument, and are used to schedule finalization of an asynchronous
1039 generator by an event loop.
1040
1041 .. versionadded:: 3.6
1042 See :pep:`525` for more details.
1043
1044 .. note::
1045 This function has been added on a provisional basis (see :pep:`411`
1046 for details.)
1047
1048
1049 .. function:: get_coroutine_origin_tracking_depth()
1050
1051 Get the current coroutine origin tracking depth, as set by
1052 :func:`set_coroutine_origin_tracking_depth`.
1053
1054 .. versionadded:: 3.7
1055
1056 .. note::
1057 This function has been added on a provisional basis (see :pep:`411`
1058 for details.) Use it only for debugging purposes.
1059
1060
1061 .. data:: hash_info
1062
1063 A :term:`named tuple` giving parameters of the numeric hash
1064 implementation. For more details about hashing of numeric types, see
1065 :ref:`numeric-hash`.
1066
1067 .. attribute:: hash_info.width
1068
1069 The width in bits used for hash values
1070
1071 .. attribute:: hash_info.modulus
1072
1073 The prime modulus P used for numeric hash scheme
1074
1075 .. attribute:: hash_info.inf
1076
1077 The hash value returned for a positive infinity
1078
1079 .. attribute:: hash_info.nan
1080
1081 (This attribute is no longer used)
1082
1083 .. attribute:: hash_info.imag
1084
1085 The multiplier used for the imaginary part of a complex number
1086
1087 .. attribute:: hash_info.algorithm
1088
1089 The name of the algorithm for hashing of str, bytes, and memoryview
1090
1091 .. attribute:: hash_info.hash_bits
1092
1093 The internal output size of the hash algorithm
1094
1095 .. attribute:: hash_info.seed_bits
1096
1097 The size of the seed key of the hash algorithm
1098
1099 .. attribute:: hash_info.cutoff
1100
1101 Cutoff for small string DJBX33A optimization in range ``[1, cutoff)``.
1102
1103 .. versionadded:: 3.2
1104
1105 .. versionchanged:: 3.4
1106 Added *algorithm*, *hash_bits*, *seed_bits*, and *cutoff*.
1107
1108
1109 .. data:: hexversion
1110
1111 The version number encoded as a single integer. This is guaranteed to increase
1112 with each version, including proper support for non-production releases. For
1113 example, to test that the Python interpreter is at least version 1.5.2, use::
1114
1115 if sys.hexversion >= 0x010502F0:
1116 # use some advanced feature
1117 ...
1118 else:
1119 # use an alternative implementation or warn the user
1120 ...
1121
1122 This is called ``hexversion`` since it only really looks meaningful when viewed
1123 as the result of passing it to the built-in :func:`hex` function. The
1124 :term:`named tuple` :data:`sys.version_info` may be used for a more
1125 human-friendly encoding of the same information.
1126
1127 More details of ``hexversion`` can be found at :ref:`apiabiversion`.
1128
1129
1130 .. data:: implementation
1131
1132 An object containing information about the implementation of the
1133 currently running Python interpreter. The following attributes are
1134 required to exist in all Python implementations.
1135
1136 *name* is the implementation's identifier, e.g. ``'cpython'``. The actual
1137 string is defined by the Python implementation, but it is guaranteed to be
1138 lower case.
1139
1140 *version* is a named tuple, in the same format as
1141 :data:`sys.version_info`. It represents the version of the Python
1142 *implementation*. This has a distinct meaning from the specific
1143 version of the Python *language* to which the currently running
1144 interpreter conforms, which ``sys.version_info`` represents. For
1145 example, for PyPy 1.8 ``sys.implementation.version`` might be
1146 ``sys.version_info(1, 8, 0, 'final', 0)``, whereas ``sys.version_info``
1147 would be ``sys.version_info(2, 7, 2, 'final', 0)``. For CPython they
1148 are the same value, since it is the reference implementation.
1149
1150 *hexversion* is the implementation version in hexadecimal format, like
1151 :data:`sys.hexversion`.
1152
1153 *cache_tag* is the tag used by the import machinery in the filenames of
1154 cached modules. By convention, it would be a composite of the
1155 implementation's name and version, like ``'cpython-33'``. However, a
1156 Python implementation may use some other value if appropriate. If
1157 ``cache_tag`` is set to ``None``, it indicates that module caching should
1158 be disabled.
1159
1160 :data:`sys.implementation` may contain additional attributes specific to
1161 the Python implementation. These non-standard attributes must start with
1162 an underscore, and are not described here. Regardless of its contents,
1163 :data:`sys.implementation` will not change during a run of the interpreter,
1164 nor between implementation versions. (It may change between Python
1165 language versions, however.) See :pep:`421` for more information.
1166
1167 .. versionadded:: 3.3
1168
1169 .. note::
1170
1171 The addition of new required attributes must go through the normal PEP
1172 process. See :pep:`421` for more information.
1173
1174 .. data:: int_info
1175
1176 A :term:`named tuple` that holds information about Python's internal
1177 representation of integers. The attributes are read only.
1178
1179 .. attribute:: int_info.bits_per_digit
1180
1181 The number of bits held in each digit.
1182 Python integers are stored internally in base ``2**int_info.bits_per_digit``.
1183
1184 .. attribute:: int_info.sizeof_digit
1185
1186 The size in bytes of the C type used to represent a digit.
1187
1188 .. attribute:: int_info.default_max_str_digits
1189
1190 The default value for :func:`sys.get_int_max_str_digits`
1191 when it is not otherwise explicitly configured.
1192
1193 .. attribute:: int_info.str_digits_check_threshold
1194
1195 The minimum non-zero value for :func:`sys.set_int_max_str_digits`,
1196 :envvar:`PYTHONINTMAXSTRDIGITS`, or :option:`-X int_max_str_digits <-X>`.
1197
1198 .. versionadded:: 3.1
1199
1200 .. versionchanged:: 3.11
1201
1202 Added :attr:`~int_info.default_max_str_digits` and
1203 :attr:`~int_info.str_digits_check_threshold`.
1204
1205
1206 .. data:: __interactivehook__
1207
1208 When this attribute exists, its value is automatically called (with no
1209 arguments) when the interpreter is launched in :ref:`interactive mode
1210 <tut-interactive>`. This is done after the :envvar:`PYTHONSTARTUP` file is
1211 read, so that you can set this hook there. The :mod:`site` module
1212 :ref:`sets this <rlcompleter-config>`.
1213
1214 .. audit-event:: cpython.run_interactivehook hook sys.__interactivehook__
1215
1216 Raises an :ref:`auditing event <auditing>`
1217 ``cpython.run_interactivehook`` with the hook object as the argument when
1218 the hook is called on startup.
1219
1220 .. versionadded:: 3.4
1221
1222
1223 .. function:: intern(string)
1224
1225 Enter *string* in the table of "interned" strings and return the interned string
1226 -- which is *string* itself or a copy. Interning strings is useful to gain a
1227 little performance on dictionary lookup -- if the keys in a dictionary are
1228 interned, and the lookup key is interned, the key comparisons (after hashing)
1229 can be done by a pointer compare instead of a string compare. Normally, the
1230 names used in Python programs are automatically interned, and the dictionaries
1231 used to hold module, class or instance attributes have interned keys.
1232
1233 Interned strings are not :term:`immortal`; you must keep a reference to the
1234 return value of :func:`intern` around to benefit from it.
1235
1236
1237 .. function:: _is_gil_enabled()
1238
1239 Return :const:`True` if the :term:`GIL` is enabled and :const:`False` if
1240 it is disabled.
1241
1242 .. versionadded:: 3.13
1243
1244 .. impl-detail::
1245
1246 It is not guaranteed to exist in all implementations of Python.
1247
1248 .. function:: is_finalizing()
1249
1250 Return :const:`True` if the main Python interpreter is
1251 :term:`shutting down <interpreter shutdown>`. Return :const:`False` otherwise.
1252
1253 See also the :exc:`PythonFinalizationError` exception.
1254
1255 .. versionadded:: 3.5
1256
1257 .. data:: last_exc
1258
1259 This variable is not always defined; it is set to the exception instance
1260 when an exception is not handled and the interpreter prints an error message
1261 and a stack traceback. Its intended use is to allow an interactive user to
1262 import a debugger module and engage in post-mortem debugging without having
1263 to re-execute the command that caused the error. (Typical use is
1264 ``import pdb; pdb.pm()`` to enter the post-mortem debugger; see :mod:`pdb`
1265 module for more information.)
1266
1267 .. versionadded:: 3.12
1268
1269 .. function:: _is_interned(string)
1270
1271 Return :const:`True` if the given string is "interned", :const:`False`
1272 otherwise.
1273
1274 .. versionadded:: 3.13
1275
1276 .. impl-detail::
1277
1278 It is not guaranteed to exist in all implementations of Python.
1279
1280
1281 .. data:: last_type
1282 last_value
1283 last_traceback
1284
1285 These three variables are deprecated; use :data:`sys.last_exc` instead.
1286 They hold the legacy representation of ``sys.last_exc``, as returned
1287 from :func:`exc_info` above.
1288
1289 .. data:: maxsize
1290
1291 An integer giving the maximum value a variable of type :c:type:`Py_ssize_t` can
1292 take. It's usually ``2**31 - 1`` on a 32-bit platform and ``2**63 - 1`` on a
1293 64-bit platform.
1294
1295
1296 .. data:: maxunicode
1297
1298 An integer giving the value of the largest Unicode code point,
1299 i.e. ``1114111`` (``0x10FFFF`` in hexadecimal).
1300
1301 .. versionchanged:: 3.3
1302 Before :pep:`393`, ``sys.maxunicode`` used to be either ``0xFFFF``
1303 or ``0x10FFFF``, depending on the configuration option that specified
1304 whether Unicode characters were stored as UCS-2 or UCS-4.
1305
1306
1307 .. data:: meta_path
1308
1309 A list of :term:`meta path finder` objects that have their
1310 :meth:`~importlib.abc.MetaPathFinder.find_spec` methods called to see if one
1311 of the objects can find the module to be imported. By default, it holds entries
1312 that implement Python's default import semantics. The
1313 :meth:`~importlib.abc.MetaPathFinder.find_spec` method is called with at
1314 least the absolute name of the module being imported. If the module to be
1315 imported is contained in a package, then the parent package's
1316 :attr:`~module.__path__`
1317 attribute is passed in as a second argument. The method returns a
1318 :term:`module spec`, or ``None`` if the module cannot be found.
1319
1320 .. seealso::
1321
1322 :class:`importlib.abc.MetaPathFinder`
1323 The abstract base class defining the interface of finder objects on
1324 :data:`meta_path`.
1325 :class:`importlib.machinery.ModuleSpec`
1326 The concrete class which
1327 :meth:`~importlib.abc.MetaPathFinder.find_spec` should return
1328 instances of.
1329
1330 .. versionchanged:: 3.4
1331
1332 :term:`Module specs <module spec>` were introduced in Python 3.4, by
1333 :pep:`451`.
1334
1335 .. versionchanged:: 3.12
1336
1337 Removed the fallback that looked for a :meth:`!find_module` method
1338 if a :data:`meta_path` entry didn't have a
1339 :meth:`~importlib.abc.MetaPathFinder.find_spec` method.
1340
1341 .. data:: modules
1342
1343 This is a dictionary that maps module names to modules which have already been
1344 loaded. This can be manipulated to force reloading of modules and other tricks.
1345 However, replacing the dictionary will not necessarily work as expected and
1346 deleting essential items from the dictionary may cause Python to fail. If
1347 you want to iterate over this global dictionary always use
1348 ``sys.modules.copy()`` or ``tuple(sys.modules)`` to avoid exceptions as its
1349 size may change during iteration as a side effect of code or activity in
1350 other threads.
1351
1352
1353 .. data:: orig_argv
1354
1355 The list of the original command line arguments passed to the Python
1356 executable.
1357
1358 The elements of :data:`sys.orig_argv` are the arguments to the Python interpreter,
1359 while the elements of :data:`sys.argv` are the arguments to the user's program.
1360 Arguments consumed by the interpreter itself will be present in :data:`sys.orig_argv`
1361 and missing from :data:`sys.argv`.
1362
1363 .. versionadded:: 3.10
1364
1365
1366 .. data:: path
1367
1368 .. index:: triple: module; search; path
1369
1370 A list of strings that specifies the search path for modules. Initialized from
1371 the environment variable :envvar:`PYTHONPATH`, plus an installation-dependent
1372 default.
1373
1374 By default, as initialized upon program startup, a potentially unsafe path
1375 is prepended to :data:`sys.path` (*before* the entries inserted as a result
1376 of :envvar:`PYTHONPATH`):
1377
1378 * ``python -m module`` command line: prepend the current working
1379 directory.
1380 * ``python script.py`` command line: prepend the script's directory.
1381 If it's a symbolic link, resolve symbolic links.
1382 * ``python -c code`` and ``python`` (REPL) command lines: prepend an empty
1383 string, which means the current working directory.
1384
1385 To not prepend this potentially unsafe path, use the :option:`-P` command
1386 line option or the :envvar:`PYTHONSAFEPATH` environment variable.
1387
1388 A program is free to modify this list for its own purposes. Only strings
1389 should be added to :data:`sys.path`; all other data types are
1390 ignored during import.
1391
1392
1393 .. seealso::
1394 * Module :mod:`site` This describes how to use .pth files to
1395 extend :data:`sys.path`.
1396
1397 .. data:: path_hooks
1398
1399 A list of callables that take a path argument to try to create a
1400 :term:`finder` for the path. If a finder can be created, it is to be
1401 returned by the callable, else raise :exc:`ImportError`.
1402
1403 Originally specified in :pep:`302`.
1404
1405
1406 .. data:: path_importer_cache
1407
1408 A dictionary acting as a cache for :term:`finder` objects. The keys are
1409 paths that have been passed to :data:`sys.path_hooks` and the values are
1410 the finders that are found. If a path is a valid file system path but no
1411 finder is found on :data:`sys.path_hooks` then ``None`` is
1412 stored.
1413
1414 Originally specified in :pep:`302`.
1415
1416
1417 .. data:: platform
1418
1419 A string containing a platform identifier. Known values are:
1420
1421 ================ ===========================
1422 System ``platform`` value
1423 ================ ===========================
1424 AIX ``'aix'``
1425 Android ``'android'``
1426 Emscripten ``'emscripten'``
1427 iOS ``'ios'``
1428 Linux ``'linux'``
1429 macOS ``'darwin'``
1430 Windows ``'win32'``
1431 Windows/Cygwin ``'cygwin'``
1432 WASI ``'wasi'``
1433 ================ ===========================
1434
1435 On Unix systems not listed in the table, the value is the lowercased OS name
1436 as returned by ``uname -s``, with the first part of the version as returned by
1437 ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, *at the time
1438 when Python was built*. Unless you want to test for a specific system
1439 version, it is therefore recommended to use the following idiom::
1440
1441 if sys.platform.startswith('freebsd'):
1442 # FreeBSD-specific code here...
1443
1444 .. versionchanged:: 3.3
1445 On Linux, :data:`sys.platform` doesn't contain the major version anymore.
1446 It is always ``'linux'``, instead of ``'linux2'`` or ``'linux3'``.
1447
1448 .. versionchanged:: 3.8
1449 On AIX, :data:`sys.platform` doesn't contain the major version anymore.
1450 It is always ``'aix'``, instead of ``'aix5'`` or ``'aix7'``.
1451
1452 .. versionchanged:: 3.13
1453 On Android, :data:`sys.platform` now returns ``'android'`` rather than
1454 ``'linux'``.
1455
1456 .. seealso::
1457
1458 :data:`os.name` has a coarser granularity. :func:`os.uname` gives
1459 system-dependent version information.
1460
1461 The :mod:`platform` module provides detailed checks for the
1462 system's identity.
1463
1464
1465 .. data:: platlibdir
1466
1467 Name of the platform-specific library directory. It is used to build the
1468 path of standard library and the paths of installed extension modules.
1469
1470 It is equal to ``"lib"`` on most platforms. On Fedora and SuSE, it is equal
1471 to ``"lib64"`` on 64-bit platforms which gives the following ``sys.path``
1472 paths (where ``X.Y`` is the Python ``major.minor`` version):
1473
1474 * ``/usr/lib64/pythonX.Y/``:
1475 Standard library (like ``os.py`` of the :mod:`os` module)
1476 * ``/usr/lib64/pythonX.Y/lib-dynload/``:
1477 C extension modules of the standard library (like the :mod:`errno` module,
1478 the exact filename is platform specific)
1479 * ``/usr/lib/pythonX.Y/site-packages/`` (always use ``lib``, not
1480 :data:`sys.platlibdir`): Third-party modules
1481 * ``/usr/lib64/pythonX.Y/site-packages/``:
1482 C extension modules of third-party packages
1483
1484 .. versionadded:: 3.9
1485
1486
1487 .. data:: prefix
1488
1489 A string giving the site-specific directory prefix where the platform
1490 independent Python files are installed; on Unix, the default is
1491 :file:`/usr/local`. This can be set at build time with the :option:`--prefix`
1492 argument to the :program:`configure` script. See
1493 :ref:`installation_paths` for derived paths.
1494
1495 .. note:: If a :ref:`virtual environment <venv-def>` is in effect, this
1496 value will be changed in ``site.py`` to point to the virtual
1497 environment. The value for the Python installation will still be
1498 available, via :data:`base_prefix`.
1499
1500
1501 .. data:: ps1
1502 ps2
1503
1504 .. index::
1505 single: interpreter prompts
1506 single: prompts, interpreter
1507 single: >>>; interpreter prompt
1508 single: ...; interpreter prompt
1509
1510 Strings specifying the primary and secondary prompt of the interpreter. These
1511 are only defined if the interpreter is in interactive mode. Their initial
1512 values in this case are ``'>>> '`` and ``'... '``. If a non-string object is
1513 assigned to either variable, its :func:`str` is re-evaluated each time the
1514 interpreter prepares to read a new interactive command; this can be used to
1515 implement a dynamic prompt.
1516
1517
1518 .. function:: setdlopenflags(n)
1519
1520 Set the flags used by the interpreter for :c:func:`dlopen` calls, such as when
1521 the interpreter loads extension modules. Among other things, this will enable a
1522 lazy resolving of symbols when importing a module, if called as
1523 ``sys.setdlopenflags(0)``. To share symbols across extension modules, call as
1524 ``sys.setdlopenflags(os.RTLD_GLOBAL)``. Symbolic names for the flag values
1525 can be found in the :mod:`os` module (:samp:`RTLD_{xxx}` constants, e.g.
1526 :const:`os.RTLD_LAZY`).
1527
1528 .. availability:: Unix.
1529
1530 .. function:: set_int_max_str_digits(maxdigits)
1531
1532 Set the :ref:`integer string conversion length limitation
1533 <int_max_str_digits>` used by this interpreter. See also
1534 :func:`get_int_max_str_digits`.
1535
1536 .. versionadded:: 3.11
1537
1538 .. function:: setprofile(profilefunc)
1539
1540 .. index::
1541 single: profile function
1542 single: profiler
1543
1544 Set the system's profile function, which allows you to implement a Python source
1545 code profiler in Python. See chapter :ref:`profile` for more information on the
1546 Python profiler. The system's profile function is called similarly to the
1547 system's trace function (see :func:`settrace`), but it is called with different events,
1548 for example it isn't called for each executed line of code (only on call and return,
1549 but the return event is reported even when an exception has been set). The function is
1550 thread-specific, but there is no way for the profiler to know about context switches between
1551 threads, so it does not make sense to use this in the presence of multiple threads. Also,
1552 its return value is not used, so it can simply return ``None``. Error in the profile
1553 function will cause itself unset.
1554
1555 .. note::
1556 The same tracing mechanism is used for :func:`!setprofile` as :func:`settrace`.
1557 To trace calls with :func:`!setprofile` inside a tracing function
1558 (e.g. in a debugger breakpoint), see :func:`call_tracing`.
1559
1560 Profile functions should have three arguments: *frame*, *event*, and
1561 *arg*. *frame* is the current stack frame. *event* is a string: ``'call'``,
1562 ``'return'``, ``'c_call'``, ``'c_return'``, or ``'c_exception'``. *arg* depends
1563 on the event type.
1564
1565 The events have the following meaning:
1566
1567 ``'call'``
1568 A function is called (or some other code block entered). The
1569 profile function is called; *arg* is ``None``.
1570
1571 ``'return'``
1572 A function (or other code block) is about to return. The profile
1573 function is called; *arg* is the value that will be returned, or ``None``
1574 if the event is caused by an exception being raised.
1575
1576 ``'c_call'``
1577 A C function is about to be called. This may be an extension function or
1578 a built-in. *arg* is the C function object.
1579
1580 ``'c_return'``
1581 A C function has returned. *arg* is the C function object.
1582
1583 ``'c_exception'``
1584 A C function has raised an exception. *arg* is the C function object.
1585
1586 .. audit-event:: sys.setprofile "" sys.setprofile
1587
1588
1589 .. function:: setrecursionlimit(limit)
1590
1591 Set the maximum depth of the Python interpreter stack to *limit*. This limit
1592 prevents infinite recursion from causing an overflow of the C stack and crashing
1593 Python.
1594
1595 The highest possible limit is platform-dependent. A user may need to set the
1596 limit higher when they have a program that requires deep recursion and a platform
1597 that supports a higher limit. This should be done with care, because a too-high
1598 limit can lead to a crash.
1599
1600 If the new limit is too low at the current recursion depth, a
1601 :exc:`RecursionError` exception is raised.
1602
1603 .. versionchanged:: 3.5.1
1604 A :exc:`RecursionError` exception is now raised if the new limit is too
1605 low at the current recursion depth.
1606
1607
1608 .. function:: setswitchinterval(interval)
1609
1610 Set the interpreter's thread switch interval (in seconds). This floating-point
1611 value determines the ideal duration of the "timeslices" allocated to
1612 concurrently running Python threads. Please note that the actual value
1613 can be higher, especially if long-running internal functions or methods
1614 are used. Also, which thread becomes scheduled at the end of the interval
1615 is the operating system's decision. The interpreter doesn't have its
1616 own scheduler.
1617
1618 .. versionadded:: 3.2
1619
1620
1621 .. function:: settrace(tracefunc)
1622
1623 .. index::
1624 single: trace function
1625 single: debugger
1626
1627 Set the system's trace function, which allows you to implement a Python
1628 source code debugger in Python. The function is thread-specific; for a
1629 debugger to support multiple threads, it must register a trace function using
1630 :func:`settrace` for each thread being debugged or use :func:`threading.settrace`.
1631
1632 Trace functions should have three arguments: *frame*, *event*, and
1633 *arg*. *frame* is the :ref:`current stack frame <frame-objects>`. *event* is a string: ``'call'``,
1634 ``'line'``, ``'return'``, ``'exception'`` or ``'opcode'``. *arg* depends on
1635 the event type.
1636
1637 The trace function is invoked (with *event* set to ``'call'``) whenever a new
1638 local scope is entered; it should return a reference to a local trace
1639 function to be used for the new scope, or ``None`` if the scope shouldn't be
1640 traced.
1641
1642 The local trace function should return a reference to itself, or to another
1643 function which would then be used as the local trace function for the scope.
1644
1645 If there is any error occurred in the trace function, it will be unset, just
1646 like ``settrace(None)`` is called.
1647
1648 .. note::
1649 Tracing is disabled while calling the trace function (e.g. a function set by
1650 :func:`!settrace`). For recursive tracing see :func:`call_tracing`.
1651
1652 The events have the following meaning:
1653
1654 ``'call'``
1655 A function is called (or some other code block entered). The
1656 global trace function is called; *arg* is ``None``; the return value
1657 specifies the local trace function.
1658
1659 ``'line'``
1660 The interpreter is about to execute a new line of code or re-execute the
1661 condition of a loop. The local trace function is called; *arg* is
1662 ``None``; the return value specifies the new local trace function. See
1663 :file:`Objects/lnotab_notes.txt` for a detailed explanation of how this
1664 works.
1665 Per-line events may be disabled for a frame by setting
1666 :attr:`~frame.f_trace_lines` to :const:`False` on that
1667 :ref:`frame <frame-objects>`.
1668
1669 ``'return'``
1670 A function (or other code block) is about to return. The local trace
1671 function is called; *arg* is the value that will be returned, or ``None``
1672 if the event is caused by an exception being raised. The trace function's
1673 return value is ignored.
1674
1675 ``'exception'``
1676 An exception has occurred. The local trace function is called; *arg* is a
1677 tuple ``(exception, value, traceback)``; the return value specifies the
1678 new local trace function.
1679
1680 ``'opcode'``
1681 The interpreter is about to execute a new opcode (see :mod:`dis` for
1682 opcode details). The local trace function is called; *arg* is
1683 ``None``; the return value specifies the new local trace function.
1684 Per-opcode events are not emitted by default: they must be explicitly
1685 requested by setting :attr:`~frame.f_trace_opcodes` to :const:`True` on the
1686 :ref:`frame <frame-objects>`.
1687
1688 Note that as an exception is propagated down the chain of callers, an
1689 ``'exception'`` event is generated at each level.
1690
1691 For more fine-grained usage, it's possible to set a trace function by
1692 assigning ``frame.f_trace = tracefunc`` explicitly, rather than relying on
1693 it being set indirectly via the return value from an already installed
1694 trace function. This is also required for activating the trace function on
1695 the current frame, which :func:`settrace` doesn't do. Note that in order
1696 for this to work, a global tracing function must have been installed
1697 with :func:`settrace` in order to enable the runtime tracing machinery,
1698 but it doesn't need to be the same tracing function (e.g. it could be a
1699 low overhead tracing function that simply returns ``None`` to disable
1700 itself immediately on each frame).
1701
1702 For more information on code and frame objects, refer to :ref:`types`.
1703
1704 .. audit-event:: sys.settrace "" sys.settrace
1705
1706 .. impl-detail::
1707
1708 The :func:`settrace` function is intended only for implementing debuggers,
1709 profilers, coverage tools and the like. Its behavior is part of the
1710 implementation platform, rather than part of the language definition, and
1711 thus may not be available in all Python implementations.
1712
1713 .. versionchanged:: 3.7
1714
1715 ``'opcode'`` event type added; :attr:`~frame.f_trace_lines` and
1716 :attr:`~frame.f_trace_opcodes` attributes added to frames
1717
1718 .. function:: set_asyncgen_hooks([firstiter] [, finalizer])
1719
1720 Accepts two optional keyword arguments which are callables that accept an
1721 :term:`asynchronous generator iterator` as an argument. The *firstiter*
1722 callable will be called when an asynchronous generator is iterated for the
1723 first time. The *finalizer* will be called when an asynchronous generator
1724 is about to be garbage collected.
1725
1726 .. audit-event:: sys.set_asyncgen_hooks_firstiter "" sys.set_asyncgen_hooks
1727
1728 .. audit-event:: sys.set_asyncgen_hooks_finalizer "" sys.set_asyncgen_hooks
1729
1730 Two auditing events are raised because the underlying API consists of two
1731 calls, each of which must raise its own event.
1732
1733 .. versionadded:: 3.6
1734 See :pep:`525` for more details, and for a reference example of a
1735 *finalizer* method see the implementation of
1736 ``asyncio.Loop.shutdown_asyncgens`` in
1737 :source:`Lib/asyncio/base_events.py`
1738
1739 .. note::
1740 This function has been added on a provisional basis (see :pep:`411`
1741 for details.)
1742
1743 .. function:: set_coroutine_origin_tracking_depth(depth)
1744
1745 Allows enabling or disabling coroutine origin tracking. When
1746 enabled, the ``cr_origin`` attribute on coroutine objects will
1747 contain a tuple of (filename, line number, function name) tuples
1748 describing the traceback where the coroutine object was created,
1749 with the most recent call first. When disabled, ``cr_origin`` will
1750 be ``None``.
1751
1752 To enable, pass a *depth* value greater than zero; this sets the
1753 number of frames whose information will be captured. To disable,
1754 pass set *depth* to zero.
1755
1756 This setting is thread-specific.
1757
1758 .. versionadded:: 3.7
1759
1760 .. note::
1761 This function has been added on a provisional basis (see :pep:`411`
1762 for details.) Use it only for debugging purposes.
1763
1764 .. function:: activate_stack_trampoline(backend, /)
1765
1766 Activate the stack profiler trampoline *backend*.
1767 The only supported backend is ``"perf"``.
1768
1769 .. availability:: Linux.
1770
1771 .. versionadded:: 3.12
1772
1773 .. seealso::
1774
1775 * :ref:`perf_profiling`
1776 * https://perf.wiki.kernel.org
1777
1778 .. function:: deactivate_stack_trampoline()
1779
1780 Deactivate the current stack profiler trampoline backend.
1781
1782 If no stack profiler is activated, this function has no effect.
1783
1784 .. availability:: Linux.
1785
1786 .. versionadded:: 3.12
1787
1788 .. function:: is_stack_trampoline_active()
1789
1790 Return ``True`` if a stack profiler trampoline is active.
1791
1792 .. availability:: Linux.
1793
1794 .. versionadded:: 3.12
1795
1796 .. function:: _enablelegacywindowsfsencoding()
1797
1798 Changes the :term:`filesystem encoding and error handler` to 'mbcs' and
1799 'replace' respectively, for consistency with versions of Python prior to
1800 3.6.
1801
1802 This is equivalent to defining the :envvar:`PYTHONLEGACYWINDOWSFSENCODING`
1803 environment variable before launching Python.
1804
1805 See also :func:`sys.getfilesystemencoding` and
1806 :func:`sys.getfilesystemencodeerrors`.
1807
1808 .. availability:: Windows.
1809
1810 .. note::
1811 Changing the filesystem encoding after Python startup is risky because
1812 the old fsencoding or paths encoded by the old fsencoding may be cached
1813 somewhere. Use :envvar:`PYTHONLEGACYWINDOWSFSENCODING` instead.
1814
1815 .. versionadded:: 3.6
1816 See :pep:`529` for more details.
1817
1818 .. deprecated-removed:: 3.13 3.16
1819 Use :envvar:`PYTHONLEGACYWINDOWSFSENCODING` instead.
1820
1821 .. data:: stdin
1822 stdout
1823 stderr
1824
1825 :term:`File objects <file object>` used by the interpreter for standard
1826 input, output and errors:
1827
1828 * ``stdin`` is used for all interactive input (including calls to
1829 :func:`input`);
1830 * ``stdout`` is used for the output of :func:`print` and :term:`expression`
1831 statements and for the prompts of :func:`input`;
1832 * The interpreter's own prompts and its error messages go to ``stderr``.
1833
1834 These streams are regular :term:`text files <text file>` like those
1835 returned by the :func:`open` function. Their parameters are chosen as
1836 follows:
1837
1838 * The encoding and error handling are initialized from
1839 :c:member:`PyConfig.stdio_encoding` and :c:member:`PyConfig.stdio_errors`.
1840
1841 On Windows, UTF-8 is used for the console device. Non-character
1842 devices such as disk files and pipes use the system locale
1843 encoding (i.e. the ANSI codepage). Non-console character
1844 devices such as NUL (i.e. where ``isatty()`` returns ``True``) use the
1845 value of the console input and output codepages at startup,
1846 respectively for stdin and stdout/stderr. This defaults to the
1847 system :term:`locale encoding` if the process is not initially attached
1848 to a console.
1849
1850 The special behaviour of the console can be overridden
1851 by setting the environment variable PYTHONLEGACYWINDOWSSTDIO
1852 before starting Python. In that case, the console codepages are
1853 used as for any other character device.
1854
1855 Under all platforms, you can override the character encoding by
1856 setting the :envvar:`PYTHONIOENCODING` environment variable before
1857 starting Python or by using the new :option:`-X` ``utf8`` command
1858 line option and :envvar:`PYTHONUTF8` environment variable. However,
1859 for the Windows console, this only applies when
1860 :envvar:`PYTHONLEGACYWINDOWSSTDIO` is also set.
1861
1862 * When interactive, the ``stdout`` stream is line-buffered. Otherwise,
1863 it is block-buffered like regular text files. The ``stderr`` stream
1864 is line-buffered in both cases. You can make both streams unbuffered
1865 by passing the :option:`-u` command-line option or setting the
1866 :envvar:`PYTHONUNBUFFERED` environment variable.
1867
1868 .. versionchanged:: 3.9
1869 Non-interactive ``stderr`` is now line-buffered instead of fully
1870 buffered.
1871
1872 .. note::
1873
1874 To write or read binary data from/to the standard streams, use the
1875 underlying binary :data:`~io.TextIOBase.buffer` object. For example, to
1876 write bytes to :data:`stdout`, use ``sys.stdout.buffer.write(b'abc')``.
1877
1878 However, if you are writing a library (and do not control in which
1879 context its code will be executed), be aware that the standard streams
1880 may be replaced with file-like objects like :class:`io.StringIO` which
1881 do not support the :attr:`!buffer` attribute.
1882
1883
1884 .. data:: __stdin__
1885 __stdout__
1886 __stderr__
1887
1888 These objects contain the original values of ``stdin``, ``stderr`` and
1889 ``stdout`` at the start of the program. They are used during finalization,
1890 and could be useful to print to the actual standard stream no matter if the
1891 ``sys.std*`` object has been redirected.
1892
1893 It can also be used to restore the actual files to known working file objects
1894 in case they have been overwritten with a broken object. However, the
1895 preferred way to do this is to explicitly save the previous stream before
1896 replacing it, and restore the saved object.
1897
1898 .. note::
1899 Under some conditions ``stdin``, ``stdout`` and ``stderr`` as well as the
1900 original values ``__stdin__``, ``__stdout__`` and ``__stderr__`` can be
1901 ``None``. It is usually the case for Windows GUI apps that aren't connected
1902 to a console and Python apps started with :program:`pythonw`.
1903
1904
1905 .. data:: stdlib_module_names
1906
1907 A frozenset of strings containing the names of standard library modules.
1908
1909 It is the same on all platforms. Modules which are not available on
1910 some platforms and modules disabled at Python build are also listed.
1911 All module kinds are listed: pure Python, built-in, frozen and extension
1912 modules. Test modules are excluded.
1913
1914 For packages, only the main package is listed: sub-packages and sub-modules
1915 are not listed. For example, the ``email`` package is listed, but the
1916 ``email.mime`` sub-package and the ``email.message`` sub-module are not
1917 listed.
1918
1919 See also the :data:`sys.builtin_module_names` list.
1920
1921 .. versionadded:: 3.10
1922
1923
1924 .. data:: thread_info
1925
1926 A :term:`named tuple` holding information about the thread
1927 implementation.
1928
1929 .. attribute:: thread_info.name
1930
1931 The name of the thread implementation:
1932
1933 * ``"nt"``: Windows threads
1934 * ``"pthread"``: POSIX threads
1935 * ``"pthread-stubs"``: stub POSIX threads
1936 (on WebAssembly platforms without threading support)
1937 * ``"solaris"``: Solaris threads
1938
1939 .. attribute:: thread_info.lock
1940
1941 The name of the lock implementation:
1942
1943 * ``"semaphore"``: a lock uses a semaphore
1944 * ``"mutex+cond"``: a lock uses a mutex and a condition variable
1945 * ``None`` if this information is unknown
1946
1947 .. attribute:: thread_info.version
1948
1949 The name and version of the thread library.
1950 It is a string, or ``None`` if this information is unknown.
1951
1952 .. versionadded:: 3.3
1953
1954
1955 .. data:: tracebacklimit
1956
1957 When this variable is set to an integer value, it determines the maximum number
1958 of levels of traceback information printed when an unhandled exception occurs.
1959 The default is ``1000``. When set to ``0`` or less, all traceback information
1960 is suppressed and only the exception type and value are printed.
1961
1962
1963 .. function:: unraisablehook(unraisable, /)
1964
1965 Handle an unraisable exception.
1966
1967 Called when an exception has occurred but there is no way for Python to
1968 handle it. For example, when a destructor raises an exception or during
1969 garbage collection (:func:`gc.collect`).
1970
1971 The *unraisable* argument has the following attributes:
1972
1973 * :attr:`!exc_type`: Exception type.
1974 * :attr:`!exc_value`: Exception value, can be ``None``.
1975 * :attr:`!exc_traceback`: Exception traceback, can be ``None``.
1976 * :attr:`!err_msg`: Error message, can be ``None``.
1977 * :attr:`!object`: Object causing the exception, can be ``None``.
1978
1979 The default hook formats :attr:`!err_msg` and :attr:`!object` as:
1980 ``f'{err_msg}: {object!r}'``; use "Exception ignored in" error message
1981 if :attr:`!err_msg` is ``None``.
1982
1983 :func:`sys.unraisablehook` can be overridden to control how unraisable
1984 exceptions are handled.
1985
1986 .. seealso::
1987
1988 :func:`excepthook` which handles uncaught exceptions.
1989
1990 .. warning::
1991
1992 Storing :attr:`!exc_value` using a custom hook can create a reference cycle.
1993 It should be cleared explicitly to break the reference cycle when the
1994 exception is no longer needed.
1995
1996 Storing :attr:`!object` using a custom hook can resurrect it if it is set to an
1997 object which is being finalized. Avoid storing :attr:`!object` after the custom
1998 hook completes to avoid resurrecting objects.
1999
2000 .. audit-event:: sys.unraisablehook hook,unraisable sys.unraisablehook
2001
2002 Raise an auditing event ``sys.unraisablehook`` with arguments
2003 *hook*, *unraisable* when an exception that cannot be handled occurs.
2004 The *unraisable* object is the same as what will be passed to the hook.
2005 If no hook has been set, *hook* may be ``None``.
2006
2007 .. versionadded:: 3.8
2008
2009 .. data:: version
2010
2011 A string containing the version number of the Python interpreter plus additional
2012 information on the build number and compiler used. This string is displayed
2013 when the interactive interpreter is started. Do not extract version information
2014 out of it, rather, use :data:`version_info` and the functions provided by the
2015 :mod:`platform` module.
2016
2017
2018 .. data:: api_version
2019
2020 The C API version for this interpreter. Programmers may find this useful when
2021 debugging version conflicts between Python and extension modules.
2022
2023
2024 .. data:: version_info
2025
2026 A tuple containing the five components of the version number: *major*, *minor*,
2027 *micro*, *releaselevel*, and *serial*. All values except *releaselevel* are
2028 integers; the release level is ``'alpha'``, ``'beta'``, ``'candidate'``, or
2029 ``'final'``. The ``version_info`` value corresponding to the Python version 2.0
2030 is ``(2, 0, 0, 'final', 0)``. The components can also be accessed by name,
2031 so ``sys.version_info[0]`` is equivalent to ``sys.version_info.major``
2032 and so on.
2033
2034 .. versionchanged:: 3.1
2035 Added named component attributes.
2036
2037 .. data:: warnoptions
2038
2039 This is an implementation detail of the warnings framework; do not modify this
2040 value. Refer to the :mod:`warnings` module for more information on the warnings
2041 framework.
2042
2043
2044 .. data:: winver
2045
2046 The version number used to form registry keys on Windows platforms. This is
2047 stored as string resource 1000 in the Python DLL. The value is normally the
2048 major and minor versions of the running Python interpreter. It is provided in the :mod:`sys`
2049 module for informational purposes; modifying this value has no effect on the
2050 registry keys used by Python.
2051
2052 .. availability:: Windows.
2053
2054
2055 .. data:: monitoring
2056 :noindex:
2057
2058 Namespace containing functions and constants for register callbacks
2059 and controlling monitoring events.
2060 See :mod:`sys.monitoring` for details.
2061
2062 .. data:: _xoptions
2063
2064 A dictionary of the various implementation-specific flags passed through
2065 the :option:`-X` command-line option. Option names are either mapped to
2066 their values, if given explicitly, or to :const:`True`. Example:
2067
2068 .. code-block:: shell-session
2069
2070 $ ./python -Xa=b -Xc
2071 Python 3.2a3+ (py3k, Oct 16 2010, 20:14:50)
2072 [GCC 4.4.3] on linux2
2073 Type "help", "copyright", "credits" or "license" for more information.
2074 >>> import sys
2075 >>> sys._xoptions
2076 {'a': 'b', 'c': True}
2077
2078 .. impl-detail::
2079
2080 This is a CPython-specific way of accessing options passed through
2081 :option:`-X`. Other implementations may export them through other
2082 means, or not at all.
2083
2084 .. versionadded:: 3.2
2085
2086
2087 .. rubric:: Citations
2088
2089 .. [C99] ISO/IEC 9899:1999. "Programming languages -- C." A public draft of this standard is available at https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf\ .