Frame Objects

Frame Objects¶
-
type PyFrameObject¶
- Part of the Limited API (as an opaque struct).
The C structure of the objects used to describe frame objects.
There are no public members in this structure.
Changed in version 3.11: The members of this structure were removed from the public C API. Refer to the What’s New entry for details.
The PyEval_GetFrame()
and PyThreadState_GetFrame()
functions
can be used to get a frame object.
See also Reflection.
-
PyTypeObject PyFrame_Type¶
The type of frame objects. It is the same object as
types.FrameType
in the Python layer.Changed in version 3.11: Previously, this type was only available after including
<frameobject.h>
.
-
PyFrameObject *PyFrame_New(PyThreadState *tstate, PyCodeObject *code, PyObject *globals, PyObject *locals)¶
Create a new frame object. This function returns a strong reference to the new frame object on success, and returns
NULL
with an exception set on failure.
-
int PyFrame_Check(PyObject *obj)¶
Return non-zero if obj is a frame object.
Changed in version 3.11: Previously, this function was only available after including
<frameobject.h>
.
-
PyFrameObject *PyFrame_GetBack(PyFrameObject *frame)¶
- Return value: New reference.
Get the frame next outer frame.
Return a strong reference, or
NULL
if frame has no outer frame.Added in version 3.9.
-
PyObject *PyFrame_GetBuiltins(PyFrameObject *frame)¶
- Return value: New reference.
Get the frame’s
f_builtins
attribute.Return a strong reference. The result cannot be
NULL
.Added in version 3.11.
-
PyCodeObject *PyFrame_GetCode(PyFrameObject *frame)¶
- Return value: New reference. Part of the Stable ABI since version 3.10.
Get the frame code.
Return a strong reference.
The result (frame code) cannot be
NULL
.Added in version 3.9.
-
PyObject *PyFrame_GetGenerator(PyFrameObject *frame)¶
- Return value: New reference.
Get the generator, coroutine, or async generator that owns this frame, or
NULL
if this frame is not owned by a generator. Does not raise an exception, even if the return value isNULL
.Return a strong reference, or
NULL
.Added in version 3.11.
-
PyObject *PyFrame_GetGlobals(PyFrameObject *frame)¶
- Return value: New reference.
Get the frame’s
f_globals
attribute.Return a strong reference. The result cannot be
NULL
.Added in version 3.11.
-
int PyFrame_GetLasti(PyFrameObject *frame)¶
Get the frame’s
f_lasti
attribute.Returns -1 if
frame.f_lasti
isNone
.Added in version 3.11.
-
PyObject *PyFrame_GetVar(PyFrameObject *frame, PyObject *name)¶
- Return value: New reference.
Get the variable name of frame.
Return a strong reference to the variable value on success.
Raise
NameError
and returnNULL
if the variable does not exist.Raise an exception and return
NULL
on error.
name type must be a
str
.Added in version 3.12.
-
PyObject *PyFrame_GetVarString(PyFrameObject *frame, const char *name)¶
- Return value: New reference.
Similar to
PyFrame_GetVar()
, but the variable name is a C string encoded in UTF-8.Added in version 3.12.
-
PyObject *PyFrame_GetLocals(PyFrameObject *frame)¶
- Return value: New reference.
Get the frame’s
f_locals
attribute. If the frame refers to an optimized scope, this returns a write-through proxy object that allows modifying the locals. In all other cases (classes, modules,exec()
,eval()
) it returns the mapping representing the frame locals directly (as described forlocals()
).Return a strong reference.
Added in version 3.11.
Changed in version 3.13: As part of PEP 667, return an instance of
PyFrameLocalsProxy_Type
.
-
int PyFrame_GetLineNumber(PyFrameObject *frame)¶
- Part of the Stable ABI since version 3.10.
Return the line number that frame is currently executing.
Frame Locals Proxies¶
Added in version 3.13.
The f_locals
attribute on a frame object
is an instance of a “frame-locals proxy”. The proxy object exposes a
write-through view of the underlying locals dictionary for the frame. This
ensures that the variables exposed by f_locals
are always up to date with
the live local variables in the frame itself.
See PEP 667 for more information.
-
PyTypeObject PyFrameLocalsProxy_Type¶
The type of frame
locals()
proxy objects.
Legacy Local Variable APIs¶
These APIs are soft deprecated. As of Python 3.13, they do nothing. They exist solely for backwards compatibility.
-
void PyFrame_LocalsToFast(PyFrameObject *f, int clear)¶
This function is soft deprecated and does nothing.
Prior to Python 3.13, this function would copy the
f_locals
attribute of f to the internal “fast” array of local variables, allowing changes in frame objects to be visible to the interpreter. If clear was true, this function would process variables that were unset in the locals dictionary.Changed in version 3.13: This function now does nothing.
-
void PyFrame_FastToLocals(PyFrameObject *f)¶
This function is soft deprecated and does nothing.
Prior to Python 3.13, this function would copy the internal “fast” array of local variables (which is used by the interpreter) to the
f_locals
attribute of f, allowing changes in local variables to be visible to frame objects.Changed in version 3.13: This function now does nothing.
-
int PyFrame_FastToLocalsWithError(PyFrameObject *f)¶
This function is soft deprecated and does nothing.
Prior to Python 3.13, this function was similar to
PyFrame_FastToLocals()
, but would return0
on success, and-1
with an exception set on failure.Changed in version 3.13: This function now does nothing.
See also
Internal Frames¶
Unless using PEP 523, you will not need this.
-
struct _PyInterpreterFrame¶
The interpreter’s internal frame representation.
Added in version 3.11.
-
PyObject *PyUnstable_InterpreterFrame_GetCode(struct _PyInterpreterFrame *frame);¶
- This is Unstable API. It may change without warning in minor releases.
Return a strong reference to the code object for the frame.
Added in version 3.12.
-
int PyUnstable_InterpreterFrame_GetLasti(struct _PyInterpreterFrame *frame);¶
- This is Unstable API. It may change without warning in minor releases.
Return the byte offset into the last executed instruction.
Added in version 3.12.
-
int PyUnstable_InterpreterFrame_GetLine(struct _PyInterpreterFrame *frame);¶
- This is Unstable API. It may change without warning in minor releases.
Return the currently executing line number, or -1 if there is no line number.
Added in version 3.12.


What Now?

13. What Now?¶
Reading this tutorial has probably reinforced your interest in using Python — you should be eager to apply Python to solving your real-world problems. Where should you go to learn more?
This tutorial is part of Python’s documentation set. Some other documents in the set are:
-
You should browse through this manual, which gives complete (though terse) reference material about types, functions, and the modules in the standard library. The standard Python distribution includes a lot of additional code. There are modules to read Unix mailboxes, retrieve documents via HTTP, generate random numbers, parse command-line options, compress data, and many other tasks. Skimming through the Library Reference will give you an idea of what’s available.
Installing Python Modules explains how to install additional modules written by other Python users.
The Python Language Reference: A detailed explanation of Python’s syntax and semantics. It’s heavy reading, but is useful as a complete guide to the language itself.
More Python resources:
https://www.python.org: The major Python website. It contains code, documentation, and pointers to Python-related pages around the web.
https://docs.python.org: Fast access to Python’s documentation.
https://pypi.org: The Python Package Index, previously also nicknamed the Cheese Shop [1], is an index of user-created Python modules that are available for download. Once you begin releasing code, you can register it here so that others can find it.
https://code.activestate.com/recipes/langs/python/: The Python Cookbook is a sizable collection of code examples, larger modules, and useful scripts. Particularly notable contributions are collected in a book also titled Python Cookbook (O’Reilly & Associates, ISBN 0-596-00797-3.)
https://pyvideo.org collects links to Python-related videos from conferences and user-group meetings.
https://scipy.org: The Scientific Python project includes modules for fast array computations and manipulations plus a host of packages for such things as linear algebra, Fourier transforms, non-linear solvers, random number distributions, statistical analysis and the like.
For Python-related questions and problem reports, you can post to the newsgroup comp.lang.python, or send them to the mailing list at python-list@python.org. The newsgroup and mailing list are gatewayed, so messages posted to one will automatically be forwarded to the other. There are hundreds of postings a day, asking (and answering) questions, suggesting new features, and announcing new modules. Mailing list archives are available at https://mail.python.org/pipermail/.
Before posting, be sure to check the list of Frequently Asked Questions (also called the FAQ). The FAQ answers many of the questions that come up again and again, and may already contain the solution for your problem.
Footnotes


11. Brief Tour of the Standard Library — Part II¶
This second tour covers more advanced modules that support professional programming needs. These modules rarely occur in small scripts.
11.1. Output Formatting¶
The reprlib
module provides a version of repr()
customized for
abbreviated displays of large or deeply nested containers:
>>> import reprlib
>>> reprlib.repr(set('supercalifragilisticexpialidocious'))
"{'a', 'c', 'd', 'e', 'f', 'g', ...}"
The pprint
module offers more sophisticated control over printing both
built-in and user defined objects in a way that is readable by the interpreter.
When the result is longer than one line, the “pretty printer” adds line breaks
and indentation to more clearly reveal data structure:
>>> import pprint
>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
... 'yellow'], 'blue']]]
...
>>> pprint.pprint(t, width=30)
[[[['black', 'cyan'],
'white',
['green', 'red']],
[['magenta', 'yellow'],
'blue']]]
The textwrap
module formats paragraphs of text to fit a given screen
width:
>>> import textwrap
>>> doc = """The wrap() method is just like fill() except that it returns
... a list of strings instead of one big string with newlines to separate
... the wrapped lines."""
...
>>> print(textwrap.fill(doc, width=40))
The wrap() method is just like fill()
except that it returns a list of strings
instead of one big string with newlines
to separate the wrapped lines.
The locale
module accesses a database of culture specific data formats.
The grouping attribute of locale’s format function provides a direct way of
formatting numbers with group separators:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
'English_United States.1252'
>>> conv = locale.localeconv() # get a mapping of conventions
>>> x = 1234567.8
>>> locale.format_string("%d", x, grouping=True)
'1,234,567'
>>> locale.format_string("%s%.*f", (conv['currency_symbol'],
... conv['frac_digits'], x), grouping=True)
'$1,234,567.80'
11.2. Templating¶
The string
module includes a versatile Template
class
with a simplified syntax suitable for editing by end-users. This allows users
to customize their applications without having to alter the application.
The format uses placeholder names formed by $
with valid Python identifiers
(alphanumeric characters and underscores). Surrounding the placeholder with
braces allows it to be followed by more alphanumeric letters with no intervening
spaces. Writing $$
creates a single escaped $
:
>>> from string import Template
>>> t = Template('${village}folk send $$10 to $cause.')
>>> t.substitute(village='Nottingham', cause='the ditch fund')
'Nottinghamfolk send $10 to the ditch fund.'
The substitute()
method raises a KeyError
when a
placeholder is not supplied in a dictionary or a keyword argument. For
mail-merge style applications, user supplied data may be incomplete and the
safe_substitute()
method may be more appropriate —
it will leave placeholders unchanged if data is missing:
>>> t = Template('Return the $item to $owner.')
>>> d = dict(item='unladen swallow')
>>> t.substitute(d)
Traceback (most recent call last):
...
KeyError: 'owner'
>>> t.safe_substitute(d)
'Return the unladen swallow to $owner.'
Template subclasses can specify a custom delimiter. For example, a batch renaming utility for a photo browser may elect to use percent signs for placeholders such as the current date, image sequence number, or file format:
>>> import time, os.path
>>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
>>> class BatchRename(Template):
... delimiter = '%'
...
>>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ')
Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f
>>> t = BatchRename(fmt)
>>> date = time.strftime('%d%b%y')
>>> for i, filename in enumerate(photofiles):
... base, ext = os.path.splitext(filename)
... newname = t.substitute(d=date, n=i, f=ext)
... print('{0} --> {1}'.format(filename, newname))
img_1074.jpg --> Ashley_0.jpg
img_1076.jpg --> Ashley_1.jpg
img_1077.jpg --> Ashley_2.jpg
Another application for templating is separating program logic from the details of multiple output formats. This makes it possible to substitute custom templates for XML files, plain text reports, and HTML web reports.
11.3. Working with Binary Data Record Layouts¶
The struct
module provides pack()
and
unpack()
functions for working with variable length binary
record formats. The following example shows
how to loop through header information in a ZIP file without using the
zipfile
module. Pack codes "H"
and "I"
represent two and four
byte unsigned numbers respectively. The "<"
indicates that they are
standard size and in little-endian byte order:
import struct
with open('myfile.zip', 'rb') as f:
data = f.read()
start = 0
for i in range(3): # show the first 3 file headers
start += 14
fields = struct.unpack('<IIIHH', data[start:start+16])
crc32, comp_size, uncomp_size, filenamesize, extra_size = fields
start += 16
filename = data[start:start+filenamesize]
start += filenamesize
extra = data[start:start+extra_size]
print(filename, hex(crc32), comp_size, uncomp_size)
start += extra_size + comp_size # skip to the next header
11.4. Multi-threading¶
Threading is a technique for decoupling tasks which are not sequentially dependent. Threads can be used to improve the responsiveness of applications that accept user input while other tasks run in the background. A related use case is running I/O in parallel with computations in another thread.
The following code shows how the high level threading
module can run
tasks in background while the main program continues to run:
import threading, zipfile
class AsyncZip(threading.Thread):
def __init__(self, infile, outfile):
threading.Thread.__init__(self)
self.infile = infile
self.outfile = outfile
def run(self):
f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
f.write(self.infile)
f.close()
print('Finished background zip of:', self.infile)
background = AsyncZip('mydata.txt', 'myarchive.zip')
background.start()
print('The main program continues to run in foreground.')
background.join() # Wait for the background task to finish
print('Main program waited until background was done.')
The principal challenge of multi-threaded applications is coordinating threads that share data or other resources. To that end, the threading module provides a number of synchronization primitives including locks, events, condition variables, and semaphores.
While those tools are powerful, minor design errors can result in problems that
are difficult to reproduce. So, the preferred approach to task coordination is
to concentrate all access to a resource in a single thread and then use the
queue
module to feed that thread with requests from other threads.
Applications using Queue
objects for inter-thread communication and
coordination are easier to design, more readable, and more reliable.
11.5. Logging¶
The logging
module offers a full featured and flexible logging system.
At its simplest, log messages are sent to a file or to sys.stderr
:
import logging
logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down')
This produces the following output:
WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down
By default, informational and debugging messages are suppressed and the output
is sent to standard error. Other output options include routing messages
through email, datagrams, sockets, or to an HTTP Server. New filters can select
different routing based on message priority: DEBUG
,
INFO
, WARNING
, ERROR
,
and CRITICAL
.
The logging system can be configured directly from Python or can be loaded from a user editable configuration file for customized logging without altering the application.
11.6. Weak References¶
Python does automatic memory management (reference counting for most objects and garbage collection to eliminate cycles). The memory is freed shortly after the last reference to it has been eliminated.
This approach works fine for most applications but occasionally there is a need
to track objects only as long as they are being used by something else.
Unfortunately, just tracking them creates a reference that makes them permanent.
The weakref
module provides tools for tracking objects without creating a
reference. When the object is no longer needed, it is automatically removed
from a weakref table and a callback is triggered for weakref objects. Typical
applications include caching objects that are expensive to create:
>>> import weakref, gc
>>> class A:
... def __init__(self, value):
... self.value = value
... def __repr__(self):
... return str(self.value)
...
>>> a = A(10) # create a reference
>>> d = weakref.WeakValueDictionary()
>>> d['primary'] = a # does not create a reference
>>> d['primary'] # fetch the object if it is still alive
10
>>> del a # remove the one reference
>>> gc.collect() # run garbage collection right away
0
>>> d['primary'] # entry was automatically removed
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
d['primary'] # entry was automatically removed
File "C:/python314/lib/weakref.py", line 46, in __getitem__
o = self.data[key]()
KeyError: 'primary'
11.7. Tools for Working with Lists¶
Many data structure needs can be met with the built-in list type. However, sometimes there is a need for alternative implementations with different performance trade-offs.
The array
module provides an array
object that is like
a list that stores only homogeneous data and stores it more compactly. The
following example shows an array of numbers stored as two byte unsigned binary
numbers (typecode "H"
) rather than the usual 16 bytes per entry for regular
lists of Python int objects:
>>> from array import array
>>> a = array('H', [4000, 10, 700, 22222])
>>> sum(a)
26932
>>> a[1:3]
array('H', [10, 700])
The collections
module provides a deque
object
that is like a list with faster appends and pops from the left side but slower
lookups in the middle. These objects are well suited for implementing queues
and breadth first tree searches:
>>> from collections import deque
>>> d = deque(["task1", "task2", "task3"])
>>> d.append("task4")
>>> print("Handling", d.popleft())
Handling task1
unsearched = deque([starting_node])
def breadth_first_search(unsearched):
node = unsearched.popleft()
for m in gen_moves(node):
if is_goal(m):
return m
unsearched.append(m)
In addition to alternative list implementations, the library also offers other
tools such as the bisect
module with functions for manipulating sorted
lists:
>>> import bisect
>>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
>>> bisect.insort(scores, (300, 'ruby'))
>>> scores
[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]
The heapq
module provides functions for implementing heaps based on
regular lists. The lowest valued entry is always kept at position zero. This
is useful for applications which repeatedly access the smallest element but do
not want to run a full list sort:
>>> from heapq import heapify, heappop, heappush
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> heapify(data) # rearrange the list into heap order
>>> heappush(data, -5) # add a new entry
>>> [heappop(data) for i in range(3)] # fetch the three smallest entries
[-5, 0, 1]
11.8. Decimal Floating-Point Arithmetic¶
The decimal
module offers a Decimal
datatype for
decimal floating-point arithmetic. Compared to the built-in float
implementation of binary floating point, the class is especially helpful for
financial applications and other uses which require exact decimal representation,
control over precision,
control over rounding to meet legal or regulatory requirements,
tracking of significant decimal places, or
applications where the user expects the results to match calculations done by hand.
For example, calculating a 5% tax on a 70 cent phone charge gives different results in decimal floating point and binary floating point. The difference becomes significant if the results are rounded to the nearest cent:
>>> from decimal import *
>>> round(Decimal('0.70') * Decimal('1.05'), 2)
Decimal('0.74')
>>> round(.70 * 1.05, 2)
0.73
The Decimal
result keeps a trailing zero, automatically
inferring four place significance from multiplicands with two place
significance. Decimal reproduces mathematics as done by hand and avoids
issues that can arise when binary floating point cannot exactly represent
decimal quantities.
Exact representation enables the Decimal
class to perform
modulo calculations and equality tests that are unsuitable for binary floating
point:
>>> Decimal('1.00') % Decimal('.10')
Decimal('0.00')
>>> 1.00 % 0.10
0.09999999999999995
>>> sum([Decimal('0.1')]*10) == Decimal('1.0')
True
>>> 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 1.0
False
The decimal
module provides arithmetic with as much precision as needed:
>>> getcontext().prec = 36
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857142857')


Integer Objects

Integer Objects¶
All integers are implemented as “long” integer objects of arbitrary size.
On error, most PyLong_As*
APIs return (return type)-1
which cannot be
distinguished from a number. Use PyErr_Occurred()
to disambiguate.
-
type PyLongObject¶
- Part of the Limited API (as an opaque struct).
This subtype of
PyObject
represents a Python integer object.
-
PyTypeObject PyLong_Type¶
- Part of the Stable ABI.
This instance of
PyTypeObject
represents the Python integer type. This is the same object asint
in the Python layer.
-
int PyLong_Check(PyObject *p)¶
Return true if its argument is a
PyLongObject
or a subtype ofPyLongObject
. This function always succeeds.
-
int PyLong_CheckExact(PyObject *p)¶
Return true if its argument is a
PyLongObject
, but not a subtype ofPyLongObject
. This function always succeeds.
-
PyObject *PyLong_FromLong(long v)¶
- Return value: New reference. Part of the Stable ABI.
Return a new
PyLongObject
object from v, orNULL
on failure.CPython implementation detail: CPython keeps an array of integer objects for all integers between
-5
and256
. When you create an int in that range you actually just get back a reference to the existing object.
-
PyObject *PyLong_FromUnsignedLong(unsigned long v)¶
- Return value: New reference. Part of the Stable ABI.
Return a new
PyLongObject
object from a C unsigned long, orNULL
on failure.
-
PyObject *PyLong_FromSsize_t(Py_ssize_t v)¶
- Return value: New reference. Part of the Stable ABI.
Return a new
PyLongObject
object from a CPy_ssize_t
, orNULL
on failure.
-
PyObject *PyLong_FromSize_t(size_t v)¶
- Return value: New reference. Part of the Stable ABI.
Return a new
PyLongObject
object from a Csize_t
, orNULL
on failure.
-
PyObject *PyLong_FromLongLong(long long v)¶
- Return value: New reference. Part of the Stable ABI.
Return a new
PyLongObject
object from a C long long, orNULL
on failure.
-
PyObject *PyLong_FromInt32(int32_t value)¶
-
PyObject *PyLong_FromInt64(int64_t value)¶
- Part of the Stable ABI since version 3.14.
Return a new
PyLongObject
object from a signed C int32_t or int64_t, orNULL
with an exception set on failure.Added in version 3.14.
-
PyObject *PyLong_FromUnsignedLongLong(unsigned long long v)¶
- Return value: New reference. Part of the Stable ABI.
Return a new
PyLongObject
object from a C unsigned long long, orNULL
on failure.
-
PyObject *PyLong_FromUInt32(uint32_t value)¶
-
PyObject *PyLong_FromUInt64(uint64_t value)¶
- Part of the Stable ABI since version 3.14.
Return a new
PyLongObject
object from an unsigned C uint32_t or uint64_t, orNULL
with an exception set on failure.Added in version 3.14.
-
PyObject *PyLong_FromDouble(double v)¶
- Return value: New reference. Part of the Stable ABI.
Return a new
PyLongObject
object from the integer part of v, orNULL
on failure.
-
PyObject *PyLong_FromString(const char *str, char **pend, int base)¶
- Return value: New reference. Part of the Stable ABI.
Return a new
PyLongObject
based on the string value in str, which is interpreted according to the radix in base, orNULL
on failure. If pend is non-NULL
, *pend will point to the end of str on success or to the first character that could not be processed on error. If base is0
, str is interpreted using the Integer literals definition; in this case, leading zeros in a non-zero decimal number raises aValueError
. If base is not0
, it must be between2
and36
, inclusive. Leading and trailing whitespace and single underscores after a base specifier and between digits are ignored. If there are no digits or str is not NULL-terminated following the digits and trailing whitespace,ValueError
will be raised.See also
PyLong_AsNativeBytes()
andPyLong_FromNativeBytes()
functions can be used to convert aPyLongObject
to/from an array of bytes in base256
.
-
PyObject *PyLong_FromUnicodeObject(PyObject *u, int base)¶
- Return value: New reference.
Convert a sequence of Unicode digits in the string u to a Python integer value.
Added in version 3.3.
-
PyObject *PyLong_FromVoidPtr(void *p)¶
- Return value: New reference. Part of the Stable ABI.
Create a Python integer from the pointer p. The pointer value can be retrieved from the resulting value using
PyLong_AsVoidPtr()
.
-
PyObject *PyLong_FromNativeBytes(const void *buffer, size_t n_bytes, int flags)¶
- Part of the Stable ABI since version 3.14.
Create a Python integer from the value contained in the first n_bytes of buffer, interpreted as a two’s-complement signed number.
flags are as for
PyLong_AsNativeBytes()
. Passing-1
will select the native endian that CPython was compiled with and assume that the most-significant bit is a sign bit. PassingPy_ASNATIVEBYTES_UNSIGNED_BUFFER
will produce the same result as callingPyLong_FromUnsignedNativeBytes()
. Other flags are ignored.Added in version 3.13.
-
PyObject *PyLong_FromUnsignedNativeBytes(const void *buffer, size_t n_bytes, int flags)¶
- Part of the Stable ABI since version 3.14.
Create a Python integer from the value contained in the first n_bytes of buffer, interpreted as an unsigned number.
flags are as for
PyLong_AsNativeBytes()
. Passing-1
will select the native endian that CPython was compiled with and assume that the most-significant bit is not a sign bit. Flags other than endian are ignored.Added in version 3.13.
-
PyLong_FromPid(pid)¶
Macro for creating a Python integer from a process identifier.
This can be defined as an alias to
PyLong_FromLong()
orPyLong_FromLongLong()
, depending on the size of the system’s PID type.Added in version 3.2.
-
long PyLong_AsLong(PyObject *obj)¶
- Part of the Stable ABI.
Return a C long representation of obj. If obj is not an instance of
PyLongObject
, first call its__index__()
method (if present) to convert it to aPyLongObject
.Raise
OverflowError
if the value of obj is out of range for a long.Returns
-1
on error. UsePyErr_Occurred()
to disambiguate.Changed in version 3.8: Use
__index__()
if available.Changed in version 3.10: This function will no longer use
__int__()
.-
long PyLong_AS_LONG(PyObject *obj)¶
A soft deprecated alias. Exactly equivalent to the preferred
PyLong_AsLong
. In particular, it can fail withOverflowError
or another exception.Deprecated since version 3.14: The function is soft deprecated.
-
long PyLong_AS_LONG(PyObject *obj)¶
-
int PyLong_AsInt(PyObject *obj)¶
- Part of the Stable ABI since version 3.13.
Similar to
PyLong_AsLong()
, but store the result in a C int instead of a C long.Added in version 3.13.
-
long PyLong_AsLongAndOverflow(PyObject *obj, int *overflow)¶
- Part of the Stable ABI.
Return a C long representation of obj. If obj is not an instance of
PyLongObject
, first call its__index__()
method (if present) to convert it to aPyLongObject
.If the value of obj is greater than
LONG_MAX
or less thanLONG_MIN
, set *overflow to1
or-1
, respectively, and return-1
; otherwise, set *overflow to0
. If any other exception occurs set *overflow to0
and return-1
as usual.Returns
-1
on error. UsePyErr_Occurred()
to disambiguate.Changed in version 3.8: Use
__index__()
if available.Changed in version 3.10: This function will no longer use
__int__()
.
-
long long PyLong_AsLongLong(PyObject *obj)¶
- Part of the Stable ABI.
Return a C long long representation of obj. If obj is not an instance of
PyLongObject
, first call its__index__()
method (if present) to convert it to aPyLongObject
.Raise
OverflowError
if the value of obj is out of range for a long long.Returns
-1
on error. UsePyErr_Occurred()
to disambiguate.Changed in version 3.8: Use
__index__()
if available.Changed in version 3.10: This function will no longer use
__int__()
.
-
long long PyLong_AsLongLongAndOverflow(PyObject *obj, int *overflow)¶
- Part of the Stable ABI.
Return a C long long representation of obj. If obj is not an instance of
PyLongObject
, first call its__index__()
method (if present) to convert it to aPyLongObject
.If the value of obj is greater than
LLONG_MAX
or less thanLLONG_MIN
, set *overflow to1
or-1
, respectively, and return-1
; otherwise, set *overflow to0
. If any other exception occurs set *overflow to0
and return-1
as usual.Returns
-1
on error. UsePyErr_Occurred()
to disambiguate.Added in version 3.2.
Changed in version 3.8: Use
__index__()
if available.Changed in version 3.10: This function will no longer use
__int__()
.
-
Py_ssize_t PyLong_AsSsize_t(PyObject *pylong)¶
- Part of the Stable ABI.
Return a C
Py_ssize_t
representation of pylong. pylong must be an instance ofPyLongObject
.Raise
OverflowError
if the value of pylong is out of range for aPy_ssize_t
.Returns
-1
on error. UsePyErr_Occurred()
to disambiguate.
-
unsigned long PyLong_AsUnsignedLong(PyObject *pylong)¶
- Part of the Stable ABI.
Return a C unsigned long representation of pylong. pylong must be an instance of
PyLongObject
.Raise
OverflowError
if the value of pylong is out of range for a unsigned long.Returns
(unsigned long)-1
on error. UsePyErr_Occurred()
to disambiguate.
-
size_t PyLong_AsSize_t(PyObject *pylong)¶
- Part of the Stable ABI.
Return a C
size_t
representation of pylong. pylong must be an instance ofPyLongObject
.Raise
OverflowError
if the value of pylong is out of range for asize_t
.Returns
(size_t)-1
on error. UsePyErr_Occurred()
to disambiguate.
-
unsigned long long PyLong_AsUnsignedLongLong(PyObject *pylong)¶
- Part of the Stable ABI.
Return a C unsigned long long representation of pylong. pylong must be an instance of
PyLongObject
.Raise
OverflowError
if the value of pylong is out of range for an unsigned long long.Returns
(unsigned long long)-1
on error. UsePyErr_Occurred()
to disambiguate.Changed in version 3.1: A negative pylong now raises
OverflowError
, notTypeError
.
-
unsigned long PyLong_AsUnsignedLongMask(PyObject *obj)¶
- Part of the Stable ABI.
Return a C unsigned long representation of obj. If obj is not an instance of
PyLongObject
, first call its__index__()
method (if present) to convert it to aPyLongObject
.If the value of obj is out of range for an unsigned long, return the reduction of that value modulo
ULONG_MAX + 1
.Returns
(unsigned long)-1
on error. UsePyErr_Occurred()
to disambiguate.Changed in version 3.8: Use
__index__()
if available.Changed in version 3.10: This function will no longer use
__int__()
.
-
unsigned long long PyLong_AsUnsignedLongLongMask(PyObject *obj)¶
- Part of the Stable ABI.
Return a C unsigned long long representation of obj. If obj is not an instance of
PyLongObject
, first call its__index__()
method (if present) to convert it to aPyLongObject
.If the value of obj is out of range for an unsigned long long, return the reduction of that value modulo
ULLONG_MAX + 1
.Returns
(unsigned long long)-1
on error. UsePyErr_Occurred()
to disambiguate.Changed in version 3.8: Use
__index__()
if available.Changed in version 3.10: This function will no longer use
__int__()
.
-
int PyLong_AsInt32(PyObject *obj, int32_t *value)¶
-
int PyLong_AsInt64(PyObject *obj, int64_t *value)¶
- Part of the Stable ABI since version 3.14.
Set *value to a signed C int32_t or int64_t representation of obj.
If obj is not an instance of
PyLongObject
, first call its__index__()
method (if present) to convert it to aPyLongObject
.If the obj value is out of range, raise an
OverflowError
.Set *value and return
0
on success. Set an exception and return-1
on error.value must not be
NULL
.Added in version 3.14.
-
int PyLong_AsUInt32(PyObject *obj, uint32_t *value)¶
-
int PyLong_AsUInt64(PyObject *obj, uint64_t *value)¶
- Part of the Stable ABI since version 3.14.
Set *value to an unsigned C uint32_t or uint64_t representation of obj.
If obj is not an instance of
PyLongObject
, first call its__index__()
method (if present) to convert it to aPyLongObject
.If obj is negative, raise a
ValueError
.If the obj value is out of range, raise an
OverflowError
.
Set *value and return
0
on success. Set an exception and return-1
on error.value must not be
NULL
.Added in version 3.14.
-
double PyLong_AsDouble(PyObject *pylong)¶
- Part of the Stable ABI.
Return a C double representation of pylong. pylong must be an instance of
PyLongObject
.Raise
OverflowError
if the value of pylong is out of range for a double.Returns
-1.0
on error. UsePyErr_Occurred()
to disambiguate.
-
void *PyLong_AsVoidPtr(PyObject *pylong)¶
- Part of the Stable ABI.
Convert a Python integer pylong to a C void pointer. If pylong cannot be converted, an
OverflowError
will be raised. This is only assured to produce a usable void pointer for values created withPyLong_FromVoidPtr()
.Returns
NULL
on error. UsePyErr_Occurred()
to disambiguate.
-
Py_ssize_t PyLong_AsNativeBytes(PyObject *pylong, void *buffer, Py_ssize_t n_bytes, int flags)¶
- Part of the Stable ABI since version 3.14.
Copy the Python integer value pylong to a native buffer of size n_bytes. The flags can be set to
-1
to behave similarly to a C cast, or to values documented below to control the behavior.Returns
-1
with an exception raised on error. This may happen if pylong cannot be interpreted as an integer, or if pylong was negative and thePy_ASNATIVEBYTES_REJECT_NEGATIVE
flag was set.Otherwise, returns the number of bytes required to store the value. If this is equal to or less than n_bytes, the entire value was copied. All n_bytes of the buffer are written: remaining bytes filled by copies of the sign bit.
If the returned value is greater than n_bytes, the value was truncated: as many of the lowest bits of the value as could fit are written, and the higher bits are ignored. This matches the typical behavior of a C-style downcast.
Note
Overflow is not considered an error. If the returned value is larger than n_bytes, most significant bits were discarded.
0
will never be returned.Values are always copied as two’s-complement.
Usage example:
int32_t value; Py_ssize_t bytes = PyLong_AsNativeBytes(pylong, &value, sizeof(value), -1); if (bytes < 0) { // Failed. A Python exception was set with the reason. return NULL; } else if (bytes <= (Py_ssize_t)sizeof(value)) { // Success! } else { // Overflow occurred, but 'value' contains the truncated // lowest bits of pylong. }
Passing zero to n_bytes will return the size of a buffer that would be large enough to hold the value. This may be larger than technically necessary, but not unreasonably so. If n_bytes=0, buffer may be
NULL
.Note
Passing n_bytes=0 to this function is not an accurate way to determine the bit length of the value.
To get at the entire Python value of an unknown size, the function can be called twice: first to determine the buffer size, then to fill it:
// Ask how much space we need. Py_ssize_t expected = PyLong_AsNativeBytes(pylong, NULL, 0, -1); if (expected < 0) { // Failed. A Python exception was set with the reason. return NULL; } assert(expected != 0); // Impossible per the API definition. uint8_t *bignum = malloc(expected); if (!bignum) { PyErr_SetString(PyExc_MemoryError, "bignum malloc failed."); return NULL; } // Safely get the entire value. Py_ssize_t bytes = PyLong_AsNativeBytes(pylong, bignum, expected, -1); if (bytes < 0) { // Exception has been set. free(bignum); return NULL; } else if (bytes > expected) { // This should not be possible. PyErr_SetString(PyExc_RuntimeError, "Unexpected bignum truncation after a size check."); free(bignum); return NULL; } // The expected success given the above pre-check. // ... use bignum ... free(bignum);
flags is either
-1
(Py_ASNATIVEBYTES_DEFAULTS
) to select defaults that behave most like a C cast, or a combination of the other flags in the table below. Note that-1
cannot be combined with other flags.Currently,
-1
corresponds toPy_ASNATIVEBYTES_NATIVE_ENDIAN | Py_ASNATIVEBYTES_UNSIGNED_BUFFER
.Flag
Value
-
Py_ASNATIVEBYTES_DEFAULTS¶
- Part of the Stable ABI since version 3.14.
-1
-
Py_ASNATIVEBYTES_BIG_ENDIAN¶
- Part of the Stable ABI since version 3.14.
0
-
Py_ASNATIVEBYTES_LITTLE_ENDIAN¶
- Part of the Stable ABI since version 3.14.
1
-
Py_ASNATIVEBYTES_NATIVE_ENDIAN¶
- Part of the Stable ABI since version 3.14.
3
-
Py_ASNATIVEBYTES_UNSIGNED_BUFFER¶
- Part of the Stable ABI since version 3.14.
4
-
Py_ASNATIVEBYTES_REJECT_NEGATIVE¶
- Part of the Stable ABI since version 3.14.
8
-
Py_ASNATIVEBYTES_ALLOW_INDEX¶
- Part of the Stable ABI since version 3.14.
16
Specifying
Py_ASNATIVEBYTES_NATIVE_ENDIAN
will override any other endian flags. Passing2
is reserved.By default, sufficient buffer will be requested to include a sign bit. For example, when converting 128 with n_bytes=1, the function will return 2 (or more) in order to store a zero sign bit.
If
Py_ASNATIVEBYTES_UNSIGNED_BUFFER
is specified, a zero sign bit will be omitted from size calculations. This allows, for example, 128 to fit in a single-byte buffer. If the destination buffer is later treated as signed, a positive input value may become negative. Note that the flag does not affect handling of negative values: for those, space for a sign bit is always requested.Specifying
Py_ASNATIVEBYTES_REJECT_NEGATIVE
causes an exception to be set if pylong is negative. Without this flag, negative values will be copied provided there is enough space for at least one sign bit, regardless of whetherPy_ASNATIVEBYTES_UNSIGNED_BUFFER
was specified.If
Py_ASNATIVEBYTES_ALLOW_INDEX
is specified and a non-integer value is passed, its__index__()
method will be called first. This may result in Python code executing and other threads being allowed to run, which could cause changes to other objects or values in use. When flags is-1
, this option is not set, and non-integer values will raiseTypeError
.Note
With the default flags (
-1
, or UNSIGNED_BUFFER without REJECT_NEGATIVE), multiple Python integers can map to a single value without overflow. For example, both255
and-1
fit a single-byte buffer and set all its bits. This matches typical C cast behavior.Added in version 3.13.
-
Py_ASNATIVEBYTES_DEFAULTS¶
-
PyLong_AsPid(pid)¶
Macro for converting a Python integer into a process identifier.
This can be defined as an alias to
PyLong_AsLong()
,PyLong_FromLongLong()
, orPyLong_AsInt()
, depending on the size of the system’s PID type.Added in version 3.2.
-
int PyLong_GetSign(PyObject *obj, int *sign)¶
Get the sign of the integer object obj.
On success, set *sign to the integer sign (0, -1 or +1 for zero, negative or positive integer, respectively) and return 0.
On failure, return -1 with an exception set. This function always succeeds if obj is a
PyLongObject
or its subtype.Added in version 3.14.
-
int PyLong_IsPositive(PyObject *obj)¶
Check if the integer object obj is positive (
obj > 0
).If obj is an instance of
PyLongObject
or its subtype, return1
when it’s positive and0
otherwise. Else set an exception and return-1
.Added in version 3.14.
-
int PyLong_IsNegative(PyObject *obj)¶
Check if the integer object obj is negative (
obj < 0
).If obj is an instance of
PyLongObject
or its subtype, return1
when it’s negative and0
otherwise. Else set an exception and return-1
.Added in version 3.14.
-
int PyLong_IsZero(PyObject *obj)¶
Check if the integer object obj is zero.
If obj is an instance of
PyLongObject
or its subtype, return1
when it’s zero and0
otherwise. Else set an exception and return-1
.Added in version 3.14.
-
PyObject *PyLong_GetInfo(void)¶
- Part of the Stable ABI.
On success, return a read only named tuple, that holds information about Python’s internal representation of integers. See
sys.int_info
for description of individual fields.On failure, return
NULL
with an exception set.Added in version 3.1.
-
int PyUnstable_Long_IsCompact(const PyLongObject *op)¶
- This is Unstable API. It may change without warning in minor releases.
Return 1 if op is compact, 0 otherwise.
This function makes it possible for performance-critical code to implement a “fast path” for small integers. For compact values use
PyUnstable_Long_CompactValue()
; for others fall back to aPyLong_As*
function orPyLong_AsNativeBytes()
.The speedup is expected to be negligible for most users.
Exactly what values are considered compact is an implementation detail and is subject to change.
Added in version 3.12.
-
Py_ssize_t PyUnstable_Long_CompactValue(const PyLongObject *op)¶
- This is Unstable API. It may change without warning in minor releases.
If op is compact, as determined by
PyUnstable_Long_IsCompact()
, return its value.Otherwise, the return value is undefined.
Added in version 3.12.
Export API¶
Added in version 3.14.
-
struct PyLongLayout¶
Layout of an array of “digits” (“limbs” in the GMP terminology), used to represent absolute value for arbitrary precision integers.
Use
PyLong_GetNativeLayout()
to get the native layout of Pythonint
objects, used internally for integers with “big enough” absolute value.See also
sys.int_info
which exposes similar information in Python.-
uint8_t bits_per_digit¶
Bits per digit. For example, a 15 bit digit means that bits 0-14 contain meaningful information.
-
uint8_t digit_size¶
Digit size in bytes. For example, a 15 bit digit will require at least 2 bytes.
-
int8_t digits_order¶
Digits order:
1
for most significant digit first-1
for least significant digit first
-
int8_t digit_endianness¶
Digit endianness:
1
for most significant byte first (big endian)-1
for least significant byte first (little endian)
-
uint8_t bits_per_digit¶
-
const PyLongLayout *PyLong_GetNativeLayout(void)¶
Get the native layout of Python
int
objects.See the
PyLongLayout
structure.The function must not be called before Python initialization nor after Python finalization. The returned layout is valid until Python is finalized. The layout is the same for all Python sub-interpreters in a process, and so it can be cached.
-
struct PyLongExport¶
Export of a Python
int
object.There are two cases:
-
Py_ssize_t ndigits¶
Number of digits in
digits
array. Only valid ifdigits
is notNULL
.
-
const void *digits¶
Read-only array of unsigned digits. Can be
NULL
.
-
Py_ssize_t ndigits¶
-
int PyLong_Export(PyObject *obj, PyLongExport *export_long)¶
Export a Python
int
object.export_long must point to a
PyLongExport
structure allocated by the caller. It must not beNULL
.On success, fill in *export_long and return
0
. On error, set an exception and return-1
.PyLong_FreeExport()
must be called when the export is no longer needed.CPython implementation detail: This function always succeeds if obj is a Python
int
object or a subclass.
-
void PyLong_FreeExport(PyLongExport *export_long)¶
Release the export export_long created by
PyLong_Export()
.CPython implementation detail: Calling
PyLong_FreeExport()
is optional if export_long->digits isNULL
.
PyLongWriter API¶
The PyLongWriter
API can be used to import an integer.
Added in version 3.14.
-
struct PyLongWriter¶
A Python
int
writer instance.The instance must be destroyed by
PyLongWriter_Finish()
orPyLongWriter_Discard()
.
-
PyLongWriter *PyLongWriter_Create(int negative, Py_ssize_t ndigits, void **digits)¶
Create a
PyLongWriter
.On success, allocate *digits and return a writer. On error, set an exception and return
NULL
.negative is
1
if the number is negative, or0
otherwise.ndigits is the number of digits in the digits array. It must be greater than 0.
digits must not be NULL.
After a successful call to this function, the caller should fill in the array of digits digits and then call
PyLongWriter_Finish()
to get a Pythonint
. The layout of digits is described byPyLong_GetNativeLayout()
.Digits must be in the range [
0
;(1 << bits_per_digit) - 1
] (where thebits_per_digit
is the number of bits per digit). Any unused most significant digits must be set to0
.Alternately, call
PyLongWriter_Discard()
to destroy the writer instance without creating anint
object.
-
PyObject *PyLongWriter_Finish(PyLongWriter *writer)¶
- Return value: New reference.
Finish a
PyLongWriter
created byPyLongWriter_Create()
.On success, return a Python
int
object. On error, set an exception and returnNULL
.The function takes care of normalizing the digits and converts the object to a compact integer if needed.
The writer instance and the digits array are invalid after the call.
-
void PyLongWriter_Discard(PyLongWriter *writer)¶
Discard a
PyLongWriter
created byPyLongWriter_Create()
.If writer is
NULL
, no operation is performed.The writer instance and the digits array are invalid after the call.
Deprecated API¶
These macros are soft deprecated. They describe parameters
of the internal representation of PyLongObject
instances.
Use PyLong_GetNativeLayout()
instead, along with PyLong_Export()
to read integer data or PyLongWriter
to write it.
These currently use the same layout, but are designed to continue working correctly
even if CPython’s internal integer representation changes.
-
PyLong_SHIFT¶
This is equivalent to
bits_per_digit
in the output ofPyLong_GetNativeLayout()
.
-
PyLong_BASE¶
This is currently equivalent to 1 << PyLong_SHIFT.
-
PyLong_MASK¶
This is currently equivalent to (1 << PyLong_SHIFT) - 1


— Encode and decode uuencode files

uu
— Encode and decode uuencode files¶
Deprecated since version 3.11, removed in version 3.13.
This module is no longer part of the Python standard library. It was removed in Python 3.13 after being deprecated in Python 3.11. The removal was decided in PEP 594.
The last version of Python that provided the uu
module was
Python 3.12.


msvcrt
— Useful routines from the MS VC++ runtime¶
These functions provide access to some useful capabilities on Windows platforms.
Some higher-level modules use these functions to build the Windows
implementations of their services. For example, the getpass
module uses
this in the implementation of the getpass()
function.
Further documentation on these functions can be found in the Platform API documentation.
The module implements both the normal and wide char variants of the console I/O api. The normal API deals only with ASCII characters and is of limited use for internationalized applications. The wide char API should be used where ever possible.
Availability: Windows.
File Operations¶
- msvcrt.locking(fd, mode, nbytes)¶
Lock part of a file based on file descriptor fd from the C runtime. Raises
OSError
on failure. The locked region of the file extends from the current file position for nbytes bytes, and may continue beyond the end of the file. mode must be one of theLK_*
constants listed below. Multiple regions in a file may be locked at the same time, but may not overlap. Adjacent regions are not merged; they must be unlocked individually.Raises an auditing event
msvcrt.locking
with argumentsfd
,mode
,nbytes
.
- msvcrt.LK_LOCK¶
- msvcrt.LK_RLCK¶
Locks the specified bytes. If the bytes cannot be locked, the program immediately tries again after 1 second. If, after 10 attempts, the bytes cannot be locked,
OSError
is raised.
- msvcrt.LK_NBLCK¶
- msvcrt.LK_NBRLCK¶
Locks the specified bytes. If the bytes cannot be locked,
OSError
is raised.
- msvcrt.LK_UNLCK¶
Unlocks the specified bytes, which must have been previously locked.
- msvcrt.setmode(fd, flags)¶
Set the line-end translation mode for the file descriptor fd. To set it to text mode, flags should be
os.O_TEXT
; for binary, it should beos.O_BINARY
.
- msvcrt.open_osfhandle(handle, flags)¶
Create a C runtime file descriptor from the file handle handle. The flags parameter should be a bitwise OR of
os.O_APPEND
,os.O_RDONLY
,os.O_TEXT
andos.O_NOINHERIT
. The returned file descriptor may be used as a parameter toos.fdopen()
to create a file object.The file descriptor is inheritable by default. Pass
os.O_NOINHERIT
flag to make it non inheritable.Raises an auditing event
msvcrt.open_osfhandle
with argumentshandle
,flags
.
- msvcrt.get_osfhandle(fd)¶
Return the file handle for the file descriptor fd. Raises
OSError
if fd is not recognized.Raises an auditing event
msvcrt.get_osfhandle
with argumentfd
.
Console I/O¶
- msvcrt.kbhit()¶
Returns a nonzero value if a keypress is waiting to be read. Otherwise, return 0.
- msvcrt.getch()¶
Read a keypress and return the resulting character as a byte string. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed. If the pressed key was a special function key, this will return
'\000'
or'\xe0'
; the next call will return the keycode. The Control-C keypress cannot be read with this function.
- msvcrt.getche()¶
Similar to
getch()
, but the keypress will be echoed if it represents a printable character.
- msvcrt.putch(char)¶
Print the byte string char to the console without buffering.
Other Functions¶
- msvcrt.heapmin()¶
Force the
malloc()
heap to clean itself up and return unused blocks to the operating system. On failure, this raisesOSError
.
- msvcrt.set_error_mode(mode)¶
Changes the location where the C runtime writes an error message for an error that might end the program. mode must be one of the
OUT_*
constants listed below orREPORT_ERRMODE
. Returns the old setting or -1 if an error occurs. Only available in debug build of Python.
- msvcrt.OUT_TO_DEFAULT¶
Error sink is determined by the app’s type. Only available in debug build of Python.
- msvcrt.OUT_TO_STDERR¶
Error sink is a standard error. Only available in debug build of Python.
- msvcrt.OUT_TO_MSGBOX¶
Error sink is a message box. Only available in debug build of Python.
- msvcrt.REPORT_ERRMODE¶
Report the current error mode value. Only available in debug build of Python.
- msvcrt.CrtSetReportMode(type, mode)¶
Specifies the destination or destinations for a specific report type generated by
_CrtDbgReport()
in the MS VC++ runtime. type must be one of theCRT_*
constants listed below. mode must be one of theCRTDBG_*
constants listed below. Only available in debug build of Python.
- msvcrt.CrtSetReportFile(type, file)¶
After you use
CrtSetReportMode()
to specifyCRTDBG_MODE_FILE
, you can specify the file handle to receive the message text. type must be one of theCRT_*
constants listed below. file should be the file handle your want specified. Only available in debug build of Python.
- msvcrt.CRT_WARN¶
Warnings, messages, and information that doesn’t need immediate attention.
- msvcrt.CRT_ERROR¶
Errors, unrecoverable problems, and issues that require immediate attention.
- msvcrt.CRT_ASSERT¶
Assertion failures.
- msvcrt.CRTDBG_MODE_DEBUG¶
Writes the message to the debugger’s output window.
- msvcrt.CRTDBG_MODE_FILE¶
Writes the message to a user-supplied file handle.
CrtSetReportFile()
should be called to define the specific file or stream to use as the destination.
- msvcrt.CRTDBG_MODE_WNDW¶
Creates a message box to display the message along with the
Abort
,Retry
, andIgnore
buttons.
- msvcrt.CRTDBG_REPORT_MODE¶
Returns current mode for the specified type.
- msvcrt.CRT_ASSEMBLY_VERSION¶
The CRT Assembly version, from the
crtassem.h
header file.
- msvcrt.VC_ASSEMBLY_PUBLICKEYTOKEN¶
The VC Assembly public key token, from the
crtassem.h
header file.
- msvcrt.LIBRARIES_ASSEMBLY_NAME_PREFIX¶
The Libraries Assembly name prefix, from the
crtassem.h
header file.