blob: 6138c63eb44b485706718854ef949349fefefaf5 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. highlightlang:: c
2
3
4.. _utilities:
5
6*********
7Utilities
8*********
9
10The functions in this chapter perform various utility tasks, ranging from
11helping C code be more portable across platforms, using Python modules from C,
12and parsing function arguments and constructing Python values from C values.
13
14
15.. _os:
16
17Operating System Utilities
18==========================
19
20
21.. cfunction:: int Py_FdIsInteractive(FILE *fp, const char *filename)
22
23 Return true (nonzero) if the standard I/O file *fp* with name *filename* is
24 deemed interactive. This is the case for files for which ``isatty(fileno(fp))``
25 is true. If the global flag :cdata:`Py_InteractiveFlag` is true, this function
26 also returns true if the *filename* pointer is *NULL* or if the name is equal to
27 one of the strings ``'<stdin>'`` or ``'???'``.
28
29
30.. cfunction:: long PyOS_GetLastModificationTime(char *filename)
31
32 Return the time of last modification of the file *filename*. The result is
33 encoded in the same way as the timestamp returned by the standard C library
34 function :cfunc:`time`.
35
36
37.. cfunction:: void PyOS_AfterFork()
38
39 Function to update some internal state after a process fork; this should be
40 called in the new process if the Python interpreter will continue to be used.
41 If a new executable is loaded into the new process, this function does not need
42 to be called.
43
44
45.. cfunction:: int PyOS_CheckStack()
46
47 Return true when the interpreter runs out of stack space. This is a reliable
48 check, but is only available when :const:`USE_STACKCHECK` is defined (currently
49 on Windows using the Microsoft Visual C++ compiler). :const:`USE_STACKCHECK`
50 will be defined automatically; you should never change the definition in your
51 own code.
52
53
54.. cfunction:: PyOS_sighandler_t PyOS_getsig(int i)
55
56 Return the current signal handler for signal *i*. This is a thin wrapper around
57 either :cfunc:`sigaction` or :cfunc:`signal`. Do not call those functions
58 directly! :ctype:`PyOS_sighandler_t` is a typedef alias for :ctype:`void
59 (\*)(int)`.
60
61
62.. cfunction:: PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h)
63
64 Set the signal handler for signal *i* to be *h*; return the old signal handler.
65 This is a thin wrapper around either :cfunc:`sigaction` or :cfunc:`signal`. Do
66 not call those functions directly! :ctype:`PyOS_sighandler_t` is a typedef
67 alias for :ctype:`void (\*)(int)`.
68
Christian Heimescbf3b5c2007-12-03 21:02:03 +000069.. _systemfunctions:
70
71System Functions
72================
73
74These are utility functions that make functionality from the :mod:`sys` module
75accessible to C code. They all work with the current interpreter thread's
76:mod:`sys` module's dict, which is contained in the internal thread state structure.
77
78.. cfunction:: PyObject *PySys_GetObject(char *name)
79
80 Return the object *name* from the :mod:`sys` module or *NULL* if it does
81 not exist, without setting an exception.
82
83.. cfunction:: FILE *PySys_GetFile(char *name, FILE *def)
84
85 Return the :ctype:`FILE*` associated with the object *name* in the
86 :mod:`sys` module, or *def* if *name* is not in the module or is not associated
87 with a :ctype:`FILE*`.
88
89.. cfunction:: int PySys_SetObject(char *name, PyObject *v)
90
91 Set *name* in the :mod:`sys` module to *v* unless *v* is *NULL*, in which
92 case *name* is deleted from the sys module. Returns ``0`` on success, ``-1``
93 on error.
94
95.. cfunction:: void PySys_ResetWarnOptions(void)
96
97 Reset :data:`sys.warnoptions` to an empty list.
98
99.. cfunction:: void PySys_AddWarnOption(char *s)
100
101 Append *s* to :data:`sys.warnoptions`.
102
103.. cfunction:: void PySys_SetPath(char *path)
104
105 Set :data:`sys.path` to a list object of paths found in *path* which should
106 be a list of paths separated with the platform's search path delimiter
107 (``:`` on Unix, ``;`` on Windows).
108
109.. cfunction:: void PySys_WriteStdout(const char *format, ...)
110
111 Write the output string described by *format* to :data:`sys.stdout`. No
112 exceptions are raised, even if truncation occurs (see below).
113
114 *format* should limit the total size of the formatted output string to
115 1000 bytes or less -- after 1000 bytes, the output string is truncated.
116 In particular, this means that no unrestricted "%s" formats should occur;
117 these should be limited using "%.<N>s" where <N> is a decimal number
118 calculated so that <N> plus the maximum size of other formatted text does not
119 exceed 1000 bytes. Also watch out for "%f", which can print hundreds of
120 digits for very large numbers.
121
122 If a problem occurs, or :data:`sys.stdout` is unset, the formatted message
123 is written to the real (C level) *stdout*.
124
125.. cfunction:: void PySys_WriteStderr(const char *format, ...)
126
127 As above, but write to :data:`sys.stderr` or *stderr* instead.
128
Georg Brandl116aa622007-08-15 14:28:22 +0000129
130.. _processcontrol:
131
132Process Control
133===============
134
135
136.. cfunction:: void Py_FatalError(const char *message)
137
138 .. index:: single: abort()
139
140 Print a fatal error message and kill the process. No cleanup is performed.
141 This function should only be invoked when a condition is detected that would
142 make it dangerous to continue using the Python interpreter; e.g., when the
143 object administration appears to be corrupted. On Unix, the standard C library
144 function :cfunc:`abort` is called which will attempt to produce a :file:`core`
145 file.
146
147
148.. cfunction:: void Py_Exit(int status)
149
150 .. index::
151 single: Py_Finalize()
152 single: exit()
153
154 Exit the current process. This calls :cfunc:`Py_Finalize` and then calls the
155 standard C library function ``exit(status)``.
156
157
158.. cfunction:: int Py_AtExit(void (*func) ())
159
160 .. index::
161 single: Py_Finalize()
162 single: cleanup functions
163
164 Register a cleanup function to be called by :cfunc:`Py_Finalize`. The cleanup
165 function will be called with no arguments and should return no value. At most
166 32 cleanup functions can be registered. When the registration is successful,
167 :cfunc:`Py_AtExit` returns ``0``; on failure, it returns ``-1``. The cleanup
168 function registered last is called first. Each cleanup function will be called
169 at most once. Since Python's internal finalization will have completed before
170 the cleanup function, no Python APIs should be called by *func*.
171
172
173.. _importing:
174
175Importing Modules
176=================
177
178
179.. cfunction:: PyObject* PyImport_ImportModule(const char *name)
180
181 .. index::
182 single: package variable; __all__
183 single: __all__ (package variable)
Georg Brandl321976b2007-09-01 12:33:24 +0000184 single: modules (in module sys)
Georg Brandl116aa622007-08-15 14:28:22 +0000185
186 This is a simplified interface to :cfunc:`PyImport_ImportModuleEx` below,
Christian Heimes072c0f12008-01-03 23:01:04 +0000187 leaving the *globals* and *locals* arguments set to *NULL* and *level* set
188 to 0. When the *name*
Georg Brandl116aa622007-08-15 14:28:22 +0000189 argument contains a dot (when it specifies a submodule of a package), the
190 *fromlist* argument is set to the list ``['*']`` so that the return value is the
191 named module rather than the top-level package containing it as would otherwise
192 be the case. (Unfortunately, this has an additional side effect when *name* in
193 fact specifies a subpackage instead of a submodule: the submodules specified in
194 the package's ``__all__`` variable are loaded.) Return a new reference to the
195 imported module, or *NULL* with an exception set on failure. Before Python 2.4,
196 the module may still be created in the failure case --- examine ``sys.modules``
197 to find out. Starting with Python 2.4, a failing import of a module no longer
198 leaves the module in ``sys.modules``.
199
Christian Heimes072c0f12008-01-03 23:01:04 +0000200
201.. cfunction:: PyObject* PyImport_ImportModuleNoBlock(const char *name)
202
Christian Heimesfaf2f632008-01-06 16:59:19 +0000203 This version of :cfunc:`PyImport_ImportModule` does not block. It's intended
Christian Heimes587c2bf2008-01-19 16:21:02 +0000204 to be used in C functions that import other modules to execute a function.
Christian Heimes072c0f12008-01-03 23:01:04 +0000205 The import may block if another thread holds the import lock. The function
Christian Heimes587c2bf2008-01-19 16:21:02 +0000206 :cfunc:`PyImport_ImportModuleNoBlock` never blocks. It first tries to fetch
Christian Heimesfaf2f632008-01-06 16:59:19 +0000207 the module from sys.modules and falls back to :cfunc:`PyImport_ImportModule`
Christian Heimes587c2bf2008-01-19 16:21:02 +0000208 unless the lock is held, in which case the function will raise an
209 :exc:`ImportError`.
Christian Heimes072c0f12008-01-03 23:01:04 +0000210
Georg Brandl116aa622007-08-15 14:28:22 +0000211
212.. cfunction:: PyObject* PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals, PyObject *fromlist)
213
214 .. index:: builtin: __import__
215
216 Import a module. This is best described by referring to the built-in Python
217 function :func:`__import__`, as the standard :func:`__import__` function calls
218 this function directly.
219
220 The return value is a new reference to the imported module or top-level package,
221 or *NULL* with an exception set on failure (before Python 2.4, the module may
222 still be created in this case). Like for :func:`__import__`, the return value
223 when a submodule of a package was requested is normally the top-level package,
224 unless a non-empty *fromlist* was given.
225
Georg Brandl321976b2007-09-01 12:33:24 +0000226 Failing imports remove incomplete module objects, like with
227 :cfunc:`PyImport_ImportModule`.
Georg Brandl116aa622007-08-15 14:28:22 +0000228
Christian Heimes072c0f12008-01-03 23:01:04 +0000229
230.. cfunction:: PyObject* PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level)
231
232 Import a module. This is best described by referring to the built-in Python
233 function :func:`__import__`, as the standard :func:`__import__` function calls
234 this function directly.
235
236 The return value is a new reference to the imported module or top-level package,
237 or *NULL* with an exception set on failure. Like for :func:`__import__`,
238 the return value when a submodule of a package was requested is normally the
239 top-level package, unless a non-empty *fromlist* was given.
240
Georg Brandl116aa622007-08-15 14:28:22 +0000241
242.. cfunction:: PyObject* PyImport_Import(PyObject *name)
243
Georg Brandl54fab812008-01-05 20:11:13 +0000244 This is a higher-level interface that calls the current "import hook
245 function" (with an explicit *level* of 0, meaning absolute import). It
246 invokes the :func:`__import__` function from the ``__builtins__`` of the
247 current globals. This means that the import is done using whatever import
248 hooks are installed in the current environment.
Christian Heimes072c0f12008-01-03 23:01:04 +0000249
Georg Brandl116aa622007-08-15 14:28:22 +0000250
251.. cfunction:: PyObject* PyImport_ReloadModule(PyObject *m)
252
253 Reload a module. Return a new reference to the reloaded module, or *NULL* with
254 an exception set on failure (the module still exists in this case).
255
256
257.. cfunction:: PyObject* PyImport_AddModule(const char *name)
258
259 Return the module object corresponding to a module name. The *name* argument
260 may be of the form ``package.module``. First check the modules dictionary if
261 there's one there, and if not, create a new one and insert it in the modules
262 dictionary. Return *NULL* with an exception set on failure.
263
264 .. note::
265
266 This function does not load or import the module; if the module wasn't already
267 loaded, you will get an empty module object. Use :cfunc:`PyImport_ImportModule`
268 or one of its variants to import a module. Package structures implied by a
269 dotted name for *name* are not created if not already present.
270
271
272.. cfunction:: PyObject* PyImport_ExecCodeModule(char *name, PyObject *co)
273
274 .. index:: builtin: compile
275
276 Given a module name (possibly of the form ``package.module``) and a code object
277 read from a Python bytecode file or obtained from the built-in function
278 :func:`compile`, load the module. Return a new reference to the module object,
279 or *NULL* with an exception set if an error occurred. Before Python 2.4, the
280 module could still be created in error cases. Starting with Python 2.4, *name*
Christian Heimesfaf2f632008-01-06 16:59:19 +0000281 is removed from :attr:`sys.modules` in error cases, and even if *name* was already
282 in :attr:`sys.modules` on entry to :cfunc:`PyImport_ExecCodeModule`. Leaving
283 incompletely initialized modules in :attr:`sys.modules` is dangerous, as imports of
Georg Brandl116aa622007-08-15 14:28:22 +0000284 such modules have no way to know that the module object is an unknown (and
285 probably damaged with respect to the module author's intents) state.
286
287 This function will reload the module if it was already imported. See
288 :cfunc:`PyImport_ReloadModule` for the intended way to reload a module.
289
290 If *name* points to a dotted name of the form ``package.module``, any package
291 structures not already created will still not be created.
292
Georg Brandl116aa622007-08-15 14:28:22 +0000293
294.. cfunction:: long PyImport_GetMagicNumber()
295
296 Return the magic number for Python bytecode files (a.k.a. :file:`.pyc` and
297 :file:`.pyo` files). The magic number should be present in the first four bytes
298 of the bytecode file, in little-endian byte order.
299
300
301.. cfunction:: PyObject* PyImport_GetModuleDict()
302
303 Return the dictionary used for the module administration (a.k.a.
304 ``sys.modules``). Note that this is a per-interpreter variable.
305
306
307.. cfunction:: void _PyImport_Init()
308
309 Initialize the import mechanism. For internal use only.
310
311
312.. cfunction:: void PyImport_Cleanup()
313
314 Empty the module table. For internal use only.
315
316
317.. cfunction:: void _PyImport_Fini()
318
319 Finalize the import mechanism. For internal use only.
320
321
322.. cfunction:: PyObject* _PyImport_FindExtension(char *, char *)
323
324 For internal use only.
325
326
327.. cfunction:: PyObject* _PyImport_FixupExtension(char *, char *)
328
329 For internal use only.
330
331
332.. cfunction:: int PyImport_ImportFrozenModule(char *name)
333
334 Load a frozen module named *name*. Return ``1`` for success, ``0`` if the
335 module is not found, and ``-1`` with an exception set if the initialization
336 failed. To access the imported module on a successful load, use
337 :cfunc:`PyImport_ImportModule`. (Note the misnomer --- this function would
338 reload the module if it was already imported.)
339
340
341.. ctype:: struct _frozen
342
343 .. index:: single: freeze utility
344
345 This is the structure type definition for frozen module descriptors, as
346 generated by the :program:`freeze` utility (see :file:`Tools/freeze/` in the
347 Python source distribution). Its definition, found in :file:`Include/import.h`,
348 is::
349
350 struct _frozen {
351 char *name;
352 unsigned char *code;
353 int size;
354 };
355
356
357.. cvar:: struct _frozen* PyImport_FrozenModules
358
359 This pointer is initialized to point to an array of :ctype:`struct _frozen`
360 records, terminated by one whose members are all *NULL* or zero. When a frozen
361 module is imported, it is searched in this table. Third-party code could play
362 tricks with this to provide a dynamically created collection of frozen modules.
363
364
365.. cfunction:: int PyImport_AppendInittab(char *name, void (*initfunc)(void))
366
367 Add a single module to the existing table of built-in modules. This is a
368 convenience wrapper around :cfunc:`PyImport_ExtendInittab`, returning ``-1`` if
369 the table could not be extended. The new module can be imported by the name
370 *name*, and uses the function *initfunc* as the initialization function called
371 on the first attempted import. This should be called before
372 :cfunc:`Py_Initialize`.
373
374
375.. ctype:: struct _inittab
376
377 Structure describing a single entry in the list of built-in modules. Each of
378 these structures gives the name and initialization function for a module built
379 into the interpreter. Programs which embed Python may use an array of these
380 structures in conjunction with :cfunc:`PyImport_ExtendInittab` to provide
381 additional built-in modules. The structure is defined in
382 :file:`Include/import.h` as::
383
384 struct _inittab {
385 char *name;
386 void (*initfunc)(void);
387 };
388
389
390.. cfunction:: int PyImport_ExtendInittab(struct _inittab *newtab)
391
392 Add a collection of modules to the table of built-in modules. The *newtab*
393 array must end with a sentinel entry which contains *NULL* for the :attr:`name`
394 field; failure to provide the sentinel value can result in a memory fault.
395 Returns ``0`` on success or ``-1`` if insufficient memory could be allocated to
396 extend the internal table. In the event of failure, no modules are added to the
397 internal table. This should be called before :cfunc:`Py_Initialize`.
398
399
400.. _marshalling-utils:
401
402Data marshalling support
403========================
404
405These routines allow C code to work with serialized objects using the same data
406format as the :mod:`marshal` module. There are functions to write data into the
407serialization format, and additional functions that can be used to read the data
408back. Files used to store marshalled data must be opened in binary mode.
409
410Numeric values are stored with the least significant byte first.
411
412The module supports two versions of the data format: version 0 is the historical
413version, version 1 (new in Python 2.4) shares interned strings in the file, and
414upon unmarshalling. *Py_MARSHAL_VERSION* indicates the current file format
415(currently 1).
416
417
418.. cfunction:: void PyMarshal_WriteLongToFile(long value, FILE *file, int version)
419
420 Marshal a :ctype:`long` integer, *value*, to *file*. This will only write the
421 least-significant 32 bits of *value*; regardless of the size of the native
Georg Brandl321976b2007-09-01 12:33:24 +0000422 :ctype:`long` type. *version* indicates the file format.
Georg Brandl116aa622007-08-15 14:28:22 +0000423
424
425.. cfunction:: void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version)
426
427 Marshal a Python object, *value*, to *file*.
Georg Brandl321976b2007-09-01 12:33:24 +0000428 *version* indicates the file format.
Georg Brandl116aa622007-08-15 14:28:22 +0000429
430
431.. cfunction:: PyObject* PyMarshal_WriteObjectToString(PyObject *value, int version)
432
433 Return a string object containing the marshalled representation of *value*.
Georg Brandl321976b2007-09-01 12:33:24 +0000434 *version* indicates the file format.
Georg Brandl116aa622007-08-15 14:28:22 +0000435
436
437The following functions allow marshalled values to be read back in.
438
439XXX What about error detection? It appears that reading past the end of the
440file will always result in a negative numeric value (where that's relevant), but
441it's not clear that negative values won't be handled properly when there's no
442error. What's the right way to tell? Should only non-negative values be written
443using these routines?
444
445
446.. cfunction:: long PyMarshal_ReadLongFromFile(FILE *file)
447
448 Return a C :ctype:`long` from the data stream in a :ctype:`FILE\*` opened for
449 reading. Only a 32-bit value can be read in using this function, regardless of
450 the native size of :ctype:`long`.
451
452
453.. cfunction:: int PyMarshal_ReadShortFromFile(FILE *file)
454
455 Return a C :ctype:`short` from the data stream in a :ctype:`FILE\*` opened for
456 reading. Only a 16-bit value can be read in using this function, regardless of
457 the native size of :ctype:`short`.
458
459
460.. cfunction:: PyObject* PyMarshal_ReadObjectFromFile(FILE *file)
461
462 Return a Python object from the data stream in a :ctype:`FILE\*` opened for
463 reading. On error, sets the appropriate exception (:exc:`EOFError` or
464 :exc:`TypeError`) and returns *NULL*.
465
466
467.. cfunction:: PyObject* PyMarshal_ReadLastObjectFromFile(FILE *file)
468
469 Return a Python object from the data stream in a :ctype:`FILE\*` opened for
470 reading. Unlike :cfunc:`PyMarshal_ReadObjectFromFile`, this function assumes
471 that no further objects will be read from the file, allowing it to aggressively
472 load file data into memory so that the de-serialization can operate from data in
473 memory rather than reading a byte at a time from the file. Only use these
474 variant if you are certain that you won't be reading anything else from the
475 file. On error, sets the appropriate exception (:exc:`EOFError` or
476 :exc:`TypeError`) and returns *NULL*.
477
478
479.. cfunction:: PyObject* PyMarshal_ReadObjectFromString(char *string, Py_ssize_t len)
480
481 Return a Python object from the data stream in a character buffer containing
482 *len* bytes pointed to by *string*. On error, sets the appropriate exception
483 (:exc:`EOFError` or :exc:`TypeError`) and returns *NULL*.
484
485
486.. _arg-parsing:
487
488Parsing arguments and building values
489=====================================
490
491These functions are useful when creating your own extensions functions and
492methods. Additional information and examples are available in
493:ref:`extending-index`.
494
495The first three of these functions described, :cfunc:`PyArg_ParseTuple`,
496:cfunc:`PyArg_ParseTupleAndKeywords`, and :cfunc:`PyArg_Parse`, all use *format
497strings* which are used to tell the function about the expected arguments. The
498format strings use the same syntax for each of these functions.
499
500A format string consists of zero or more "format units." A format unit
501describes one Python object; it is usually a single character or a parenthesized
502sequence of format units. With a few exceptions, a format unit that is not a
503parenthesized sequence normally corresponds to a single address argument to
504these functions. In the following description, the quoted form is the format
505unit; the entry in (round) parentheses is the Python object type that matches
506the format unit; and the entry in [square] brackets is the type of the C
507variable(s) whose address should be passed.
508
509``s`` (string or Unicode object) [const char \*]
510 Convert a Python string or Unicode object to a C pointer to a character string.
511 You must not provide storage for the string itself; a pointer to an existing
512 string is stored into the character pointer variable whose address you pass.
513 The C string is NUL-terminated. The Python string must not contain embedded NUL
514 bytes; if it does, a :exc:`TypeError` exception is raised. Unicode objects are
515 converted to C strings using the default encoding. If this conversion fails, a
516 :exc:`UnicodeError` is raised.
517
518``s#`` (string, Unicode or any read buffer compatible object) [const char \*, int]
519 This variant on ``s`` stores into two C variables, the first one a pointer to a
520 character string, the second one its length. In this case the Python string may
521 contain embedded null bytes. Unicode objects pass back a pointer to the default
522 encoded string version of the object if such a conversion is possible. All
523 other read-buffer compatible objects pass back a reference to the raw internal
524 data representation.
525
526``y`` (bytes object) [const char \*]
527 This variant on ``s`` convert a Python bytes object to a C pointer to a
528 character string. The bytes object must not contain embedded NUL bytes; if it
529 does, a :exc:`TypeError` exception is raised.
530
531``y#`` (bytes object) [const char \*, int]
532 This variant on ``s#`` stores into two C variables, the first one a pointer to a
533 character string, the second one its length. This only accepts bytes objects.
534
535``z`` (string or ``None``) [const char \*]
536 Like ``s``, but the Python object may also be ``None``, in which case the C
537 pointer is set to *NULL*.
538
539``z#`` (string or ``None`` or any read buffer compatible object) [const char \*, int]
540 This is to ``s#`` as ``z`` is to ``s``.
541
542``u`` (Unicode object) [Py_UNICODE \*]
543 Convert a Python Unicode object to a C pointer to a NUL-terminated buffer of
544 16-bit Unicode (UTF-16) data. As with ``s``, there is no need to provide
545 storage for the Unicode data buffer; a pointer to the existing Unicode data is
546 stored into the :ctype:`Py_UNICODE` pointer variable whose address you pass.
547
548``u#`` (Unicode object) [Py_UNICODE \*, int]
549 This variant on ``u`` stores into two C variables, the first one a pointer to a
550 Unicode data buffer, the second one its length. Non-Unicode objects are handled
551 by interpreting their read-buffer pointer as pointer to a :ctype:`Py_UNICODE`
552 array.
553
Guido van Rossumfb67be22007-08-29 18:38:11 +0000554``Z`` (Unicode or ``None``) [Py_UNICODE \*]
555 Like ``s``, but the Python object may also be ``None``, in which case the C
556 pointer is set to *NULL*.
557
558``Z#`` (Unicode or ``None``) [Py_UNICODE \*, int]
559 This is to ``u#`` as ``Z`` is to ``u``.
560
Georg Brandl116aa622007-08-15 14:28:22 +0000561``es`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer]
562 This variant on ``s`` is used for encoding Unicode and objects convertible to
563 Unicode into a character buffer. It only works for encoded data without embedded
564 NUL bytes.
565
566 This format requires two arguments. The first is only used as input, and
567 must be a :ctype:`const char\*` which points to the name of an encoding as a
568 NUL-terminated string, or *NULL*, in which case the default encoding is used.
569 An exception is raised if the named encoding is not known to Python. The
570 second argument must be a :ctype:`char\*\*`; the value of the pointer it
571 references will be set to a buffer with the contents of the argument text.
572 The text will be encoded in the encoding specified by the first argument.
573
574 :cfunc:`PyArg_ParseTuple` will allocate a buffer of the needed size, copy the
575 encoded data into this buffer and adjust *\*buffer* to reference the newly
576 allocated storage. The caller is responsible for calling :cfunc:`PyMem_Free` to
577 free the allocated buffer after use.
578
579``et`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer]
580 Same as ``es`` except that 8-bit string objects are passed through without
581 recoding them. Instead, the implementation assumes that the string object uses
582 the encoding passed in as parameter.
583
584``es#`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer, int \*buffer_length]
585 This variant on ``s#`` is used for encoding Unicode and objects convertible to
586 Unicode into a character buffer. Unlike the ``es`` format, this variant allows
587 input data which contains NUL characters.
588
589 It requires three arguments. The first is only used as input, and must be a
590 :ctype:`const char\*` which points to the name of an encoding as a
591 NUL-terminated string, or *NULL*, in which case the default encoding is used.
592 An exception is raised if the named encoding is not known to Python. The
593 second argument must be a :ctype:`char\*\*`; the value of the pointer it
594 references will be set to a buffer with the contents of the argument text.
595 The text will be encoded in the encoding specified by the first argument.
596 The third argument must be a pointer to an integer; the referenced integer
597 will be set to the number of bytes in the output buffer.
598
599 There are two modes of operation:
600
601 If *\*buffer* points a *NULL* pointer, the function will allocate a buffer of
602 the needed size, copy the encoded data into this buffer and set *\*buffer* to
603 reference the newly allocated storage. The caller is responsible for calling
604 :cfunc:`PyMem_Free` to free the allocated buffer after usage.
605
606 If *\*buffer* points to a non-*NULL* pointer (an already allocated buffer),
607 :cfunc:`PyArg_ParseTuple` will use this location as the buffer and interpret the
608 initial value of *\*buffer_length* as the buffer size. It will then copy the
609 encoded data into the buffer and NUL-terminate it. If the buffer is not large
610 enough, a :exc:`ValueError` will be set.
611
612 In both cases, *\*buffer_length* is set to the length of the encoded data
613 without the trailing NUL byte.
614
615``et#`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer]
616 Same as ``es#`` except that string objects are passed through without recoding
617 them. Instead, the implementation assumes that the string object uses the
618 encoding passed in as parameter.
619
620``b`` (integer) [char]
621 Convert a Python integer to a tiny int, stored in a C :ctype:`char`.
622
623``B`` (integer) [unsigned char]
624 Convert a Python integer to a tiny int without overflow checking, stored in a C
625 :ctype:`unsigned char`.
626
Georg Brandl116aa622007-08-15 14:28:22 +0000627``h`` (integer) [short int]
628 Convert a Python integer to a C :ctype:`short int`.
629
630``H`` (integer) [unsigned short int]
631 Convert a Python integer to a C :ctype:`unsigned short int`, without overflow
632 checking.
633
Georg Brandl116aa622007-08-15 14:28:22 +0000634``i`` (integer) [int]
635 Convert a Python integer to a plain C :ctype:`int`.
636
637``I`` (integer) [unsigned int]
638 Convert a Python integer to a C :ctype:`unsigned int`, without overflow
639 checking.
640
Georg Brandl116aa622007-08-15 14:28:22 +0000641``l`` (integer) [long int]
642 Convert a Python integer to a C :ctype:`long int`.
643
644``k`` (integer) [unsigned long]
Georg Brandlaacc0892007-12-02 23:11:00 +0000645 Convert a Python integer to a C :ctype:`unsigned long` without
Georg Brandl116aa622007-08-15 14:28:22 +0000646 overflow checking.
647
Georg Brandl116aa622007-08-15 14:28:22 +0000648``L`` (integer) [PY_LONG_LONG]
649 Convert a Python integer to a C :ctype:`long long`. This format is only
650 available on platforms that support :ctype:`long long` (or :ctype:`_int64` on
651 Windows).
652
653``K`` (integer) [unsigned PY_LONG_LONG]
Georg Brandlaacc0892007-12-02 23:11:00 +0000654 Convert a Python integer to a C :ctype:`unsigned long long`
Georg Brandl116aa622007-08-15 14:28:22 +0000655 without overflow checking. This format is only available on platforms that
656 support :ctype:`unsigned long long` (or :ctype:`unsigned _int64` on Windows).
657
Georg Brandl116aa622007-08-15 14:28:22 +0000658``n`` (integer) [Py_ssize_t]
Georg Brandlaacc0892007-12-02 23:11:00 +0000659 Convert a Python integer to a C :ctype:`Py_ssize_t`.
Georg Brandl116aa622007-08-15 14:28:22 +0000660
Georg Brandl116aa622007-08-15 14:28:22 +0000661``c`` (string of length 1) [char]
662 Convert a Python character, represented as a string of length 1, to a C
663 :ctype:`char`.
664
665``f`` (float) [float]
666 Convert a Python floating point number to a C :ctype:`float`.
667
668``d`` (float) [double]
669 Convert a Python floating point number to a C :ctype:`double`.
670
671``D`` (complex) [Py_complex]
672 Convert a Python complex number to a C :ctype:`Py_complex` structure.
673
674``O`` (object) [PyObject \*]
675 Store a Python object (without any conversion) in a C object pointer. The C
676 program thus receives the actual object that was passed. The object's reference
677 count is not increased. The pointer stored is not *NULL*.
678
679``O!`` (object) [*typeobject*, PyObject \*]
680 Store a Python object in a C object pointer. This is similar to ``O``, but
681 takes two C arguments: the first is the address of a Python type object, the
682 second is the address of the C variable (of type :ctype:`PyObject\*`) into which
683 the object pointer is stored. If the Python object does not have the required
684 type, :exc:`TypeError` is raised.
685
686``O&`` (object) [*converter*, *anything*]
687 Convert a Python object to a C variable through a *converter* function. This
688 takes two arguments: the first is a function, the second is the address of a C
689 variable (of arbitrary type), converted to :ctype:`void \*`. The *converter*
690 function in turn is called as follows::
691
692 status = converter(object, address);
693
694 where *object* is the Python object to be converted and *address* is the
695 :ctype:`void\*` argument that was passed to the :cfunc:`PyArg_Parse\*` function.
696 The returned *status* should be ``1`` for a successful conversion and ``0`` if
697 the conversion has failed. When the conversion fails, the *converter* function
698 should raise an exception.
699
700``S`` (string) [PyStringObject \*]
701 Like ``O`` but requires that the Python object is a string object. Raises
702 :exc:`TypeError` if the object is not a string object. The C variable may also
703 be declared as :ctype:`PyObject\*`.
704
705``U`` (Unicode string) [PyUnicodeObject \*]
706 Like ``O`` but requires that the Python object is a Unicode object. Raises
707 :exc:`TypeError` if the object is not a Unicode object. The C variable may also
708 be declared as :ctype:`PyObject\*`.
709
710``t#`` (read-only character buffer) [char \*, int]
711 Like ``s#``, but accepts any object which implements the read-only buffer
712 interface. The :ctype:`char\*` variable is set to point to the first byte of
713 the buffer, and the :ctype:`int` is set to the length of the buffer. Only
714 single-segment buffer objects are accepted; :exc:`TypeError` is raised for all
715 others.
716
717``w`` (read-write character buffer) [char \*]
718 Similar to ``s``, but accepts any object which implements the read-write buffer
719 interface. The caller must determine the length of the buffer by other means,
720 or use ``w#`` instead. Only single-segment buffer objects are accepted;
721 :exc:`TypeError` is raised for all others.
722
723``w#`` (read-write character buffer) [char \*, int]
724 Like ``s#``, but accepts any object which implements the read-write buffer
725 interface. The :ctype:`char \*` variable is set to point to the first byte of
726 the buffer, and the :ctype:`int` is set to the length of the buffer. Only
727 single-segment buffer objects are accepted; :exc:`TypeError` is raised for all
728 others.
729
730``(items)`` (tuple) [*matching-items*]
731 The object must be a Python sequence whose length is the number of format units
732 in *items*. The C arguments must correspond to the individual format units in
733 *items*. Format units for sequences may be nested.
734
Georg Brandlaacc0892007-12-02 23:11:00 +0000735It is possible to pass "long" integers (integers whose value exceeds the
736platform's :const:`LONG_MAX`) however no proper range checking is done --- the
737most significant bits are silently truncated when the receiving field is too
738small to receive the value (actually, the semantics are inherited from downcasts
739in C --- your mileage may vary).
Georg Brandl116aa622007-08-15 14:28:22 +0000740
741A few other characters have a meaning in a format string. These may not occur
742inside nested parentheses. They are:
743
744``|``
745 Indicates that the remaining arguments in the Python argument list are optional.
746 The C variables corresponding to optional arguments should be initialized to
747 their default value --- when an optional argument is not specified,
748 :cfunc:`PyArg_ParseTuple` does not touch the contents of the corresponding C
749 variable(s).
750
751``:``
752 The list of format units ends here; the string after the colon is used as the
753 function name in error messages (the "associated value" of the exception that
754 :cfunc:`PyArg_ParseTuple` raises).
755
756``;``
757 The list of format units ends here; the string after the semicolon is used as
758 the error message *instead* of the default error message. Clearly, ``:`` and
759 ``;`` mutually exclude each other.
760
761Note that any Python object references which are provided to the caller are
762*borrowed* references; do not decrement their reference count!
763
764Additional arguments passed to these functions must be addresses of variables
765whose type is determined by the format string; these are used to store values
766from the input tuple. There are a few cases, as described in the list of format
767units above, where these parameters are used as input values; they should match
768what is specified for the corresponding format unit in that case.
769
770For the conversion to succeed, the *arg* object must match the format and the
771format must be exhausted. On success, the :cfunc:`PyArg_Parse\*` functions
772return true, otherwise they return false and raise an appropriate exception.
773
774
775.. cfunction:: int PyArg_ParseTuple(PyObject *args, const char *format, ...)
776
777 Parse the parameters of a function that takes only positional parameters into
778 local variables. Returns true on success; on failure, it returns false and
779 raises the appropriate exception.
780
781
782.. cfunction:: int PyArg_VaParse(PyObject *args, const char *format, va_list vargs)
783
784 Identical to :cfunc:`PyArg_ParseTuple`, except that it accepts a va_list rather
785 than a variable number of arguments.
786
787
788.. cfunction:: int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], ...)
789
790 Parse the parameters of a function that takes both positional and keyword
791 parameters into local variables. Returns true on success; on failure, it
792 returns false and raises the appropriate exception.
793
794
795.. cfunction:: int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], va_list vargs)
796
797 Identical to :cfunc:`PyArg_ParseTupleAndKeywords`, except that it accepts a
798 va_list rather than a variable number of arguments.
799
800
Georg Brandl85eb8c12007-08-31 16:33:38 +0000801.. XXX deprecated, will be removed
Georg Brandl116aa622007-08-15 14:28:22 +0000802.. cfunction:: int PyArg_Parse(PyObject *args, const char *format, ...)
803
804 Function used to deconstruct the argument lists of "old-style" functions ---
805 these are functions which use the :const:`METH_OLDARGS` parameter parsing
806 method. This is not recommended for use in parameter parsing in new code, and
807 most code in the standard interpreter has been modified to no longer use this
808 for that purpose. It does remain a convenient way to decompose other tuples,
809 however, and may continue to be used for that purpose.
810
811
812.. cfunction:: int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
813
814 A simpler form of parameter retrieval which does not use a format string to
815 specify the types of the arguments. Functions which use this method to retrieve
816 their parameters should be declared as :const:`METH_VARARGS` in function or
817 method tables. The tuple containing the actual parameters should be passed as
818 *args*; it must actually be a tuple. The length of the tuple must be at least
819 *min* and no more than *max*; *min* and *max* may be equal. Additional
820 arguments must be passed to the function, each of which should be a pointer to a
821 :ctype:`PyObject\*` variable; these will be filled in with the values from
822 *args*; they will contain borrowed references. The variables which correspond
823 to optional parameters not given by *args* will not be filled in; these should
824 be initialized by the caller. This function returns true on success and false if
825 *args* is not a tuple or contains the wrong number of elements; an exception
826 will be set if there was a failure.
827
828 This is an example of the use of this function, taken from the sources for the
829 :mod:`_weakref` helper module for weak references::
830
831 static PyObject *
832 weakref_ref(PyObject *self, PyObject *args)
833 {
834 PyObject *object;
835 PyObject *callback = NULL;
836 PyObject *result = NULL;
837
838 if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) {
839 result = PyWeakref_NewRef(object, callback);
840 }
841 return result;
842 }
843
844 The call to :cfunc:`PyArg_UnpackTuple` in this example is entirely equivalent to
845 this call to :cfunc:`PyArg_ParseTuple`::
846
847 PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
848
Georg Brandl116aa622007-08-15 14:28:22 +0000849
850.. cfunction:: PyObject* Py_BuildValue(const char *format, ...)
851
852 Create a new value based on a format string similar to those accepted by the
853 :cfunc:`PyArg_Parse\*` family of functions and a sequence of values. Returns
854 the value or *NULL* in the case of an error; an exception will be raised if
855 *NULL* is returned.
856
857 :cfunc:`Py_BuildValue` does not always build a tuple. It builds a tuple only if
858 its format string contains two or more format units. If the format string is
859 empty, it returns ``None``; if it contains exactly one format unit, it returns
860 whatever object is described by that format unit. To force it to return a tuple
861 of size 0 or one, parenthesize the format string.
862
863 When memory buffers are passed as parameters to supply data to build objects, as
864 for the ``s`` and ``s#`` formats, the required data is copied. Buffers provided
865 by the caller are never referenced by the objects created by
866 :cfunc:`Py_BuildValue`. In other words, if your code invokes :cfunc:`malloc`
867 and passes the allocated memory to :cfunc:`Py_BuildValue`, your code is
868 responsible for calling :cfunc:`free` for that memory once
869 :cfunc:`Py_BuildValue` returns.
870
871 In the following description, the quoted form is the format unit; the entry in
872 (round) parentheses is the Python object type that the format unit will return;
873 and the entry in [square] brackets is the type of the C value(s) to be passed.
874
875 The characters space, tab, colon and comma are ignored in format strings (but
876 not within format units such as ``s#``). This can be used to make long format
877 strings a tad more readable.
878
879 ``s`` (string) [char \*]
880 Convert a null-terminated C string to a Python object. If the C string pointer
881 is *NULL*, ``None`` is used.
882
883 ``s#`` (string) [char \*, int]
884 Convert a C string and its length to a Python object. If the C string pointer
885 is *NULL*, the length is ignored and ``None`` is returned.
886
887 ``z`` (string or ``None``) [char \*]
888 Same as ``s``.
889
890 ``z#`` (string or ``None``) [char \*, int]
891 Same as ``s#``.
892
893 ``u`` (Unicode string) [Py_UNICODE \*]
894 Convert a null-terminated buffer of Unicode (UCS-2 or UCS-4) data to a Python
895 Unicode object. If the Unicode buffer pointer is *NULL*, ``None`` is returned.
896
897 ``u#`` (Unicode string) [Py_UNICODE \*, int]
898 Convert a Unicode (UCS-2 or UCS-4) data buffer and its length to a Python
899 Unicode object. If the Unicode buffer pointer is *NULL*, the length is ignored
900 and ``None`` is returned.
901
902 ``U`` (string) [char \*]
903 Convert a null-terminated C string to a Python unicode object. If the C string
904 pointer is *NULL*, ``None`` is used.
905
906 ``U#`` (string) [char \*, int]
907 Convert a C string and its length to a Python unicode object. If the C string
908 pointer is *NULL*, the length is ignored and ``None`` is returned.
909
910 ``i`` (integer) [int]
911 Convert a plain C :ctype:`int` to a Python integer object.
912
913 ``b`` (integer) [char]
914 Convert a plain C :ctype:`char` to a Python integer object.
915
916 ``h`` (integer) [short int]
917 Convert a plain C :ctype:`short int` to a Python integer object.
918
919 ``l`` (integer) [long int]
920 Convert a C :ctype:`long int` to a Python integer object.
921
922 ``B`` (integer) [unsigned char]
923 Convert a C :ctype:`unsigned char` to a Python integer object.
924
925 ``H`` (integer) [unsigned short int]
926 Convert a C :ctype:`unsigned short int` to a Python integer object.
927
928 ``I`` (integer/long) [unsigned int]
Martin v. Löwis327858e2007-12-04 22:18:27 +0000929 Convert a C :ctype:`unsigned int` to a Python long integer object.
Georg Brandl116aa622007-08-15 14:28:22 +0000930
931 ``k`` (integer/long) [unsigned long]
Martin v. Löwis327858e2007-12-04 22:18:27 +0000932 Convert a C :ctype:`unsigned long` to a Python long integer object.
Georg Brandl116aa622007-08-15 14:28:22 +0000933
934 ``L`` (long) [PY_LONG_LONG]
Georg Brandlaacc0892007-12-02 23:11:00 +0000935 Convert a C :ctype:`long long` to a Python integer object. Only available
Georg Brandl116aa622007-08-15 14:28:22 +0000936 on platforms that support :ctype:`long long`.
937
938 ``K`` (long) [unsigned PY_LONG_LONG]
Georg Brandlaacc0892007-12-02 23:11:00 +0000939 Convert a C :ctype:`unsigned long long` to a Python integer object. Only
Georg Brandl116aa622007-08-15 14:28:22 +0000940 available on platforms that support :ctype:`unsigned long long`.
941
942 ``n`` (int) [Py_ssize_t]
Georg Brandlaacc0892007-12-02 23:11:00 +0000943 Convert a C :ctype:`Py_ssize_t` to a Python integer.
Georg Brandl116aa622007-08-15 14:28:22 +0000944
Georg Brandl116aa622007-08-15 14:28:22 +0000945 ``c`` (string of length 1) [char]
946 Convert a C :ctype:`int` representing a character to a Python string of length
947 1.
948
949 ``d`` (float) [double]
950 Convert a C :ctype:`double` to a Python floating point number.
951
952 ``f`` (float) [float]
953 Same as ``d``.
954
955 ``D`` (complex) [Py_complex \*]
956 Convert a C :ctype:`Py_complex` structure to a Python complex number.
957
958 ``O`` (object) [PyObject \*]
959 Pass a Python object untouched (except for its reference count, which is
960 incremented by one). If the object passed in is a *NULL* pointer, it is assumed
961 that this was caused because the call producing the argument found an error and
962 set an exception. Therefore, :cfunc:`Py_BuildValue` will return *NULL* but won't
963 raise an exception. If no exception has been raised yet, :exc:`SystemError` is
964 set.
965
966 ``S`` (object) [PyObject \*]
967 Same as ``O``.
968
969 ``N`` (object) [PyObject \*]
970 Same as ``O``, except it doesn't increment the reference count on the object.
971 Useful when the object is created by a call to an object constructor in the
972 argument list.
973
974 ``O&`` (object) [*converter*, *anything*]
975 Convert *anything* to a Python object through a *converter* function. The
976 function is called with *anything* (which should be compatible with :ctype:`void
977 \*`) as its argument and should return a "new" Python object, or *NULL* if an
978 error occurred.
979
980 ``(items)`` (tuple) [*matching-items*]
981 Convert a sequence of C values to a Python tuple with the same number of items.
982
983 ``[items]`` (list) [*matching-items*]
984 Convert a sequence of C values to a Python list with the same number of items.
985
986 ``{items}`` (dictionary) [*matching-items*]
987 Convert a sequence of C values to a Python dictionary. Each pair of consecutive
988 C values adds one item to the dictionary, serving as key and value,
989 respectively.
990
991 If there is an error in the format string, the :exc:`SystemError` exception is
992 set and *NULL* returned.
993
994
995.. _string-conversion:
996
997String conversion and formatting
998================================
999
1000Functions for number conversion and formatted string output.
1001
1002
1003.. cfunction:: int PyOS_snprintf(char *str, size_t size, const char *format, ...)
1004
1005 Output not more than *size* bytes to *str* according to the format string
1006 *format* and the extra arguments. See the Unix man page :manpage:`snprintf(2)`.
1007
1008
1009.. cfunction:: int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)
1010
1011 Output not more than *size* bytes to *str* according to the format string
1012 *format* and the variable argument list *va*. Unix man page
1013 :manpage:`vsnprintf(2)`.
1014
1015:cfunc:`PyOS_snprintf` and :cfunc:`PyOS_vsnprintf` wrap the Standard C library
1016functions :cfunc:`snprintf` and :cfunc:`vsnprintf`. Their purpose is to
1017guarantee consistent behavior in corner cases, which the Standard C functions do
1018not.
1019
1020The wrappers ensure that *str*[*size*-1] is always ``'\0'`` upon return. They
1021never write more than *size* bytes (including the trailing ``'\0'``) into str.
1022Both functions require that ``str != NULL``, ``size > 0`` and ``format !=
1023NULL``.
1024
1025If the platform doesn't have :cfunc:`vsnprintf` and the buffer size needed to
1026avoid truncation exceeds *size* by more than 512 bytes, Python aborts with a
1027*Py_FatalError*.
1028
1029The return value (*rv*) for these functions should be interpreted as follows:
1030
1031* When ``0 <= rv < size``, the output conversion was successful and *rv*
1032 characters were written to *str* (excluding the trailing ``'\0'`` byte at
1033 *str*[*rv*]).
1034
1035* When ``rv >= size``, the output conversion was truncated and a buffer with
1036 ``rv + 1`` bytes would have been needed to succeed. *str*[*size*-1] is ``'\0'``
1037 in this case.
1038
1039* When ``rv < 0``, "something bad happened." *str*[*size*-1] is ``'\0'`` in
1040 this case too, but the rest of *str* is undefined. The exact cause of the error
1041 depends on the underlying platform.
1042
1043The following functions provide locale-independent string to number conversions.
1044
1045
1046.. cfunction:: double PyOS_ascii_strtod(const char *nptr, char **endptr)
1047
1048 Convert a string to a :ctype:`double`. This function behaves like the Standard C
1049 function :cfunc:`strtod` does in the C locale. It does this without changing the
1050 current locale, since that would not be thread-safe.
1051
1052 :cfunc:`PyOS_ascii_strtod` should typically be used for reading configuration
1053 files or other non-user input that should be locale independent.
1054
Georg Brandl116aa622007-08-15 14:28:22 +00001055 See the Unix man page :manpage:`strtod(2)` for details.
1056
1057
1058.. cfunction:: char * PyOS_ascii_formatd(char *buffer, size_t buf_len, const char *format, double d)
1059
1060 Convert a :ctype:`double` to a string using the ``'.'`` as the decimal
1061 separator. *format* is a :cfunc:`printf`\ -style format string specifying the
1062 number format. Allowed conversion characters are ``'e'``, ``'E'``, ``'f'``,
1063 ``'F'``, ``'g'`` and ``'G'``.
1064
1065 The return value is a pointer to *buffer* with the converted string or NULL if
1066 the conversion failed.
1067
Georg Brandl116aa622007-08-15 14:28:22 +00001068
1069.. cfunction:: double PyOS_ascii_atof(const char *nptr)
1070
1071 Convert a string to a :ctype:`double` in a locale-independent way.
1072
Georg Brandl116aa622007-08-15 14:28:22 +00001073 See the Unix man page :manpage:`atof(2)` for details.
1074
Christian Heimes99170a52007-12-19 02:07:34 +00001075
1076.. cfunction:: char * PyOS_stricmp(char *s1, char *s2)
1077
1078 Case insensitive comparsion of strings. The functions works almost
1079 identical to :cfunc:`strcmp` except that it ignores the case.
1080
Christian Heimes99170a52007-12-19 02:07:34 +00001081
1082.. cfunction:: char * PyOS_strnicmp(char *s1, char *s2, Py_ssize_t size)
1083
1084 Case insensitive comparsion of strings. The functions works almost
1085 identical to :cfunc:`strncmp` except that it ignores the case.
1086
Christian Heimesd8654cf2007-12-02 15:22:16 +00001087
1088.. _reflection:
1089
1090Reflection
1091==========
1092
1093.. cfunction:: PyObject* PyEval_GetBuiltins()
1094
1095 Return a dictionary of the builtins in the current execution frame,
1096 or the interpreter of the thread state if no frame is currently executing.
1097
1098
1099.. cfunction:: PyObject* PyEval_GetLocals()
1100
1101 Return a dictionary of the local variables in the current execution frame,
1102 or *NULL* if no frame is currently executing.
1103
1104
1105.. cfunction:: PyObject* PyEval_GetGlobals()
1106
1107 Return a dictionary of the global variables in the current execution frame,
1108 or *NULL* if no frame is currently executing.
1109
1110
1111.. cfunction:: PyFrameObject* PyEval_GetFrame()
1112
1113 Return the current thread state's frame, which is *NULL* if no frame is
1114 currently executing.
1115
1116
1117.. cfunction:: int PyEval_GetRestricted()
1118
1119 If there is a current frame and it is executing in restricted mode, return true,
1120 otherwise false.
1121
1122
1123.. cfunction:: const char* PyEval_GetFuncName(PyObject *func)
1124
1125 Return the name of *func* if it is a function, class or instance object, else the
1126 name of *func*\s type.
1127
1128
1129.. cfunction:: const char* PyEval_GetFuncDesc(PyObject *func)
1130
1131 Return a description string, depending on the type of *func*.
1132 Return values include "()" for functions and methods, " constructor",
1133 " instance", and " object". Concatenated with the result of
1134 :cfunc:`PyEval_GetFuncName`, the result will be a description of
1135 *func*.