rest25/c-api/init.rst => rest262/c-api/init.rst
97   separate, independent versions of all imported modules, including the
98   fundamental modules :mod:`__builtin__`, :mod:`__main__` and :mod:`sys`.  The
99   table of loaded modules (``sys.modules``) and the module search path
100   (``sys.path``) are also separate.  The new environment has no ``sys.argv``
101   variable.  It has new standard I/O stream file objects ``sys.stdin``,
102   ``sys.stdout`` and ``sys.stderr`` (however these refer to the same underlying
103   :ctype:`FILE` structures in the C library).
104
n105-   The return value points to the first thread state created in the new sub-
n105+   The return value points to the first thread state created in the new
106-   interpreter.  This thread state is made in the current thread state.  Note that
106+   sub-interpreter.  This thread state is made in the current thread state.
107-   no actual thread is created; see the discussion of thread states below.  If
107+   Note that no actual thread is created; see the discussion of thread states
108-   creation of the new interpreter is unsuccessful, *NULL* is returned; no
108+   below.  If creation of the new interpreter is unsuccessful, *NULL* is
109-   exception is set since the exception state is stored in the current thread state
109+   returned; no exception is set since the exception state is stored in the
110-   and there may not be a current thread state.  (Like all other Python/C API
110+   current thread state and there may not be a current thread state.  (Like all
111-   functions, the global interpreter lock must be held before calling this function
111+   other Python/C API functions, the global interpreter lock must be held before
112-   and is still held when it returns; however, unlike most other Python/C API
112+   calling this function and is still held when it returns; however, unlike most
113-   functions, there needn't be a current thread state on entry.)
113+   other Python/C API functions, there needn't be a current thread state on
114+   entry.)
114
115   .. index::
116      single: Py_Finalize()
117      single: Py_Initialize()
118
119   Extension modules are shared between (sub-)interpreters as follows: the first
120   time a particular extension is imported, it is initialized normally, and a
121   (shallow) copy of its module's dictionary is squirreled away.  When the same
164
165.. cfunction:: void Py_SetProgramName(char *name)
166
167   .. index::
168      single: Py_Initialize()
169      single: main()
170      single: Py_GetPath()
171
n172-   This function should be called before :cfunc:`Py_Initialize` is called for the
n173+   This function should be called before :cfunc:`Py_Initialize` is called for
173-   first time, if it is called at all.  It tells the interpreter the value of the
174+   the first time, if it is called at all.  It tells the interpreter the value
174-   ``argv[0]`` argument to the :cfunc:`main` function of the program.  This is used
175+   of the ``argv[0]`` argument to the :cfunc:`main` function of the program.
175-   by :cfunc:`Py_GetPath` and some other functions below to find the Python run-
176+   This is used by :cfunc:`Py_GetPath` and some other functions below to find
176-   time libraries relative to the interpreter executable.  The default value is
177+   the Python run-time libraries relative to the interpreter executable.  The
177-   ``'python'``.  The argument should point to a zero-terminated character string
178+   default value is ``'python'``.  The argument should point to a
178-   in static storage whose contents will not change for the duration of the
179+   zero-terminated character string in static storage whose contents will not
179-   program's execution.  No code in the Python interpreter will change the contents
180+   change for the duration of the program's execution.  No code in the Python
180-   of this storage.
181+   interpreter will change the contents of this storage.
181
182
183.. cfunction:: char* Py_GetProgramName()
184
185   .. index:: single: Py_SetProgramName()
186
187   Return the program name set with :cfunc:`Py_SetProgramName`, or the default.
188   The returned string points into static storage; the caller should not modify its
199   value.  This corresponds to the :makevar:`prefix` variable in the top-level
200   :file:`Makefile` and the :option:`--prefix` argument to the :program:`configure`
201   script at build time.  The value is available to Python code as ``sys.prefix``.
202   It is only useful on Unix.  See also the next function.
203
204
205.. cfunction:: char* Py_GetExecPrefix()
206
n207-   Return the *exec-prefix* for installed platform-*de*pendent files.  This is
n208+   Return the *exec-prefix* for installed platform-*dependent* files.  This is
208   derived through a number of complicated rules from the program name set with
209   :cfunc:`Py_SetProgramName` and some environment variables; for example, if the
210   program name is ``'/usr/local/bin/python'``, the exec-prefix is
211   ``'/usr/local'``.  The returned string points into static storage; the caller
212   should not modify its value.  This corresponds to the :makevar:`exec_prefix`
213   variable in the top-level :file:`Makefile` and the :option:`--exec-prefix`
214   argument to the :program:`configure` script at build  time.  The value is
215   available to Python code as ``sys.exec_prefix``.  It is only useful on Unix.
254
255   .. index::
256      triple: module; search; path
257      single: path (in module sys)
258
259   Return the default module search path; this is computed from the  program name
260   (set by :cfunc:`Py_SetProgramName` above) and some environment variables.  The
261   returned string consists of a series of directory names separated by a platform
n262-   dependent delimiter character.  The delimiter character is ``':'`` on Unixand
n263+   dependent delimiter character.  The delimiter character is ``':'`` on Unix and
263   Mac OS X, ``';'`` on Windows.  The returned string points into static storage;
264   the caller should not modify its value.  The value is available to Python code
265   as the list ``sys.path``, which may be modified to change the future search path
266   for loaded modules.
267
n268-   .. % XXX should give the exact rules
n269+   .. XXX should give the exact rules
269
270
271.. cfunction:: const char* Py_GetVersion()
272
273   Return the version of this Python interpreter.  This is a string that looks
274   something like ::
275
276      "1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]"
347
348.. cfunction:: void PySys_SetArgv(int argc, char **argv)
349
350   .. index::
351      single: main()
352      single: Py_FatalError()
353      single: argv (in module sys)
354
n355-   Set ``sys.argv`` based on *argc* and *argv*.  These parameters are similar to
n356+   Set :data:`sys.argv` based on *argc* and *argv*.  These parameters are
356-   those passed to the program's :cfunc:`main` function with the difference that
357+   similar to those passed to the program's :cfunc:`main` function with the
357-   the first entry should refer to the script file to be executed rather than the
358+   difference that the first entry should refer to the script file to be
358-   executable hosting the Python interpreter.  If there isn't a script that will be
359+   executed rather than the executable hosting the Python interpreter.  If there
359-   run, the first entry in *argv* can be an empty string.  If this function fails
360+   isn't a script that will be run, the first entry in *argv* can be an empty
360-   to initialize ``sys.argv``, a fatal condition is signalled using
361+   string.  If this function fails to initialize :data:`sys.argv`, a fatal
361-   :cfunc:`Py_FatalError`.
362+   condition is signalled using :cfunc:`Py_FatalError`.
362
n364+   This function also prepends the executed script's path to :data:`sys.path`.
365+   If no script is executed (in the case of calling ``python -c`` or just the
366+   interactive interpreter), the empty string is used instead.
367+ 
363-   .. % XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
368+   .. XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
364-   .. % check w/ Guido.
369+      check w/ Guido.
365
n366-.. % XXX Other PySys thingies (doesn't really belong in this chapter)
n371+ 
372+.. cfunction:: void Py_SetPythonHome(char *home)
373+ 
374+   Set the default "home" directory, that is, the location of the standard
375+   Python libraries.  The libraries are searched in
376+   :file:`{home}/lib/python{version}` and :file:`{home}/lib/python{version}`.
377+ 
378+ 
379+.. cfunction:: char* Py_GetPythonHome()
380+ 
381+   Return the default "home", that is, the value set by a previous call to
382+   :cfunc:`Py_SetPythonHome`, or the value of the :envvar:`PYTHONHOME`
383+   environment variable if it is set.
367
368
369.. _threads:
370
371Thread State and the Global Interpreter Lock
372============================================
373
374.. index::
375   single: global interpreter lock
376   single: interpreter lock
377   single: lock, interpreter
378
n379-The Python interpreter is not fully thread safe.  In order to support multi-
n396+The Python interpreter is not fully thread safe.  In order to support
380-threaded Python programs, there's a global lock that must be held by the current
397+multi-threaded Python programs, there's a global lock, called the :dfn:`global
398+interpreter lock` or :dfn:`GIL`, that must be held by the current thread before
381-thread before it can safely access Python objects. Without the lock, even the
399+it can safely access Python objects. Without the lock, even the simplest
382-simplest operations could cause problems in a multi-threaded program: for
400+operations could cause problems in a multi-threaded program: for example, when
383-example, when two threads simultaneously increment the reference count of the
401+two threads simultaneously increment the reference count of the same object, the
384-same object, the reference count could end up being incremented only once
402+reference count could end up being incremented only once instead of twice.
385-instead of twice.
386
387.. index:: single: setcheckinterval() (in module sys)
388
389Therefore, the rule exists that only the thread that has acquired the global
390interpreter lock may operate on Python objects or call Python/C API functions.
391In order to support multi-threaded Python programs, the interpreter regularly
392releases and reacquires the lock --- by default, every 100 bytecode instructions
393(this can be changed with  :func:`sys.setcheckinterval`).  The lock is also
406store "per-thread global data," Python's internal platform independent thread
407abstraction doesn't support this yet.  Therefore, the current thread state must
408be manipulated explicitly.
409
410This is easy enough in most cases.  Most code manipulating the global
411interpreter lock has the following simple structure::
412
413   Save the thread state in a local variable.
n414-   Release the interpreter lock.
n431+   Release the global interpreter lock.
415   ...Do some blocking I/O operation...
n416-   Reacquire the interpreter lock.
n433+   Reacquire the global interpreter lock.
417   Restore the thread state from the local variable.
418
419This is so common that a pair of macros exists to simplify it::
420
421   Py_BEGIN_ALLOW_THREADS
422   ...Do some blocking I/O operation...
423   Py_END_ALLOW_THREADS
424
425.. index::
426   single: Py_BEGIN_ALLOW_THREADS
427   single: Py_END_ALLOW_THREADS
428
429The :cmacro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a
430hidden local variable; the :cmacro:`Py_END_ALLOW_THREADS` macro closes the
431block.  Another advantage of using these two macros is that when Python is
432compiled without thread support, they are defined empty, thus saving the thread
n433-state and lock manipulations.
n450+state and GIL manipulations.
434
435When thread support is enabled, the block above expands to the following code::
436
437   PyThreadState *_save;
438
439   _save = PyEval_SaveThread();
440   ...Do some blocking I/O operation...
441   PyEval_RestoreThread(_save);
457   single: PyEval_SaveThread()
458   single: PyEval_ReleaseLock()
459   single: PyEval_AcquireLock()
460
461There are some subtle differences; in particular, :cfunc:`PyEval_RestoreThread`
462saves and restores the value of the  global variable :cdata:`errno`, since the
463lock manipulation does not guarantee that :cdata:`errno` is left alone.  Also,
464when thread support is disabled, :cfunc:`PyEval_SaveThread` and
n465-:cfunc:`PyEval_RestoreThread` don't manipulate the lock; in this case,
n482+:cfunc:`PyEval_RestoreThread` don't manipulate the GIL; in this case,
466:cfunc:`PyEval_ReleaseLock` and :cfunc:`PyEval_AcquireLock` are not available.
467This is done so that dynamically loaded extensions compiled with thread support
468enabled can be loaded by an interpreter that was compiled with disabled thread
469support.
470
471The global interpreter lock is used to protect the pointer to the current thread
472state.  When releasing the lock and saving the thread state, the current thread
473state pointer must be retrieved before the lock is released (since another
540
541   .. index:: single: Py_Initialize()
542
543   This is a no-op when called for a second time.  It is safe to call this function
544   before calling :cfunc:`Py_Initialize`.
545
546   .. index:: module: thread
547
n548-   When only the main thread exists, no lock operations are needed. This is a
n565+   When only the main thread exists, no GIL operations are needed. This is a
549   common situation (most Python programs do not use threads), and the lock
n550-   operations slow the interpreter down a bit. Therefore, the lock is not created
n567+   operations slow the interpreter down a bit. Therefore, the lock is not
551-   initially.  This situation is equivalent to having acquired the lock:  when
568+   created initially.  This situation is equivalent to having acquired the lock:
552-   there is only a single thread, all object accesses are safe.  Therefore, when
569+   when there is only a single thread, all object accesses are safe.  Therefore,
553-   this function initializes the lock, it also acquires it.  Before the Python
570+   when this function initializes the global interpreter lock, it also acquires
554-   :mod:`thread` module creates a new thread, knowing that either it has the lock
571+   it.  Before the Python :mod:`thread` module creates a new thread, knowing
555-   or the lock hasn't been created yet, it calls :cfunc:`PyEval_InitThreads`.  When
572+   that either it has the lock or the lock hasn't been created yet, it calls
556-   this call returns, it is guaranteed that the lock has been created and that the
573+   :cfunc:`PyEval_InitThreads`.  When this call returns, it is guaranteed that
557-   calling thread has acquired it.
574+   the lock has been created and that the calling thread has acquired it.
558
559   It is **not** safe to call this function when it is unknown which thread (if
560   any) currently has the global interpreter lock.
561
562   This function is not available when thread support is disabled at compile time.
563
564
565.. cfunction:: int PyEval_ThreadsInitialized()
566
567   Returns a non-zero value if :cfunc:`PyEval_InitThreads` has been called.  This
n568-   function can be called without holding the lock, and therefore can be used to
n585+   function can be called without holding the GIL, and therefore can be used to
569   avoid calls to the locking API when running single-threaded.  This function is
570   not available when thread support is disabled at compile time.
571
572   .. versionadded:: 2.4
573
574
575.. cfunction:: void PyEval_AcquireLock()
576
600   thread.  The *tstate* argument, which must not be *NULL*, is only used to check
601   that it represents the current thread state --- if it isn't, a fatal error is
602   reported. This function is not available when thread support is disabled at
603   compile time.
604
605
606.. cfunction:: PyThreadState* PyEval_SaveThread()
607
n608-   Release the interpreter lock (if it has been created and thread support is
n625+   Release the global interpreter lock (if it has been created and thread
609-   enabled) and reset the thread state to *NULL*, returning the previous thread
626+   support is enabled) and reset the thread state to *NULL*, returning the
610-   state (which is not *NULL*).  If the lock has been created, the current thread
627+   previous thread state (which is not *NULL*).  If the lock has been created,
611-   must have acquired it.  (This function is available even when thread support is
628+   the current thread must have acquired it.  (This function is available even
612-   disabled at compile time.)
629+   when thread support is disabled at compile time.)
613
614
615.. cfunction:: void PyEval_RestoreThread(PyThreadState *tstate)
616
n617-   Acquire the interpreter lock (if it has been created and thread support is
n634+   Acquire the global interpreter lock (if it has been created and thread
618-   enabled) and set the thread state to *tstate*, which must not be *NULL*.  If the
635+   support is enabled) and set the thread state to *tstate*, which must not be
619-   lock has been created, the current thread must not have acquired it, otherwise
636+   *NULL*.  If the lock has been created, the current thread must not have
620-   deadlock ensues.  (This function is available even when thread support is
637+   acquired it, otherwise deadlock ensues.  (This function is available even
621-   disabled at compile time.)
638+   when thread support is disabled at compile time.)
639+ 
640+ 
641+.. cfunction:: void PyEval_ReInitThreads()
642+ 
643+   This function is called from :cfunc:`PyOS_AfterFork` to ensure that newly
644+   created child processes don't hold locks referring to threads which
645+   are not running in the child process.
646+ 
622
623The following macros are normally used without a trailing semicolon; look for
624example usage in the Python source distribution.
625
626
627.. cmacro:: Py_BEGIN_ALLOW_THREADS
628
629   This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();``.
649
650.. cmacro:: Py_UNBLOCK_THREADS
651
652   This macro expands to ``_save = PyEval_SaveThread();``: it is equivalent to
653   :cmacro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable
654   declaration.  It is a no-op when thread support is disabled at compile time.
655
656All of the following functions are only available when thread support is enabled
n657-at compile time, and must be called only when the interpreter lock has been
n682+at compile time, and must be called only when the global interpreter lock has
658-created.
683+been created.
659
660
661.. cfunction:: PyInterpreterState* PyInterpreterState_New()
662
n663-   Create a new interpreter state object.  The interpreter lock need not be held,
n688+   Create a new interpreter state object.  The global interpreter lock need not
664-   but may be held if it is necessary to serialize calls to this function.
689+   be held, but may be held if it is necessary to serialize calls to this
690+   function.
665
666
667.. cfunction:: void PyInterpreterState_Clear(PyInterpreterState *interp)
668
n669-   Reset all information in an interpreter state object.  The interpreter lock must
n695+   Reset all information in an interpreter state object.  The global interpreter
670-   be held.
696+   lock must be held.
671
672
673.. cfunction:: void PyInterpreterState_Delete(PyInterpreterState *interp)
674
n675-   Destroy an interpreter state object.  The interpreter lock need not be held.
n701+   Destroy an interpreter state object.  The global interpreter lock need not be
676-   The interpreter state must have been reset with a previous call to
702+   held.  The interpreter state must have been reset with a previous call to
677   :cfunc:`PyInterpreterState_Clear`.
678
679
680.. cfunction:: PyThreadState* PyThreadState_New(PyInterpreterState *interp)
681
n682-   Create a new thread state object belonging to the given interpreter object.  The
n708+   Create a new thread state object belonging to the given interpreter object.
683-   interpreter lock need not be held, but may be held if it is necessary to
709+   The global interpreter lock need not be held, but may be held if it is
684-   serialize calls to this function.
710+   necessary to serialize calls to this function.
685
686
687.. cfunction:: void PyThreadState_Clear(PyThreadState *tstate)
688
n689-   Reset all information in a thread state object.  The interpreter lock must be
n715+   Reset all information in a thread state object.  The global interpreter lock
690-   held.
716+   must be held.
691
692
693.. cfunction:: void PyThreadState_Delete(PyThreadState *tstate)
694
n695-   Destroy a thread state object.  The interpreter lock need not be held.  The
n721+   Destroy a thread state object.  The global interpreter lock need not be held.
696-   thread state must have been reset with a previous call to
722+   The thread state must have been reset with a previous call to
697   :cfunc:`PyThreadState_Clear`.
698
699
700.. cfunction:: PyThreadState* PyThreadState_Get()
701
n702-   Return the current thread state.  The interpreter lock must be held.  When the
n728+   Return the current thread state.  The global interpreter lock must be held.
703-   current thread state is *NULL*, this issues a fatal error (so that the caller
729+   When the current thread state is *NULL*, this issues a fatal error (so that
704-   needn't check for *NULL*).
730+   the caller needn't check for *NULL*).
705
706
707.. cfunction:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate)
708
709   Swap the current thread state with the thread state given by the argument
n710-   *tstate*, which may be *NULL*.  The interpreter lock must be held.
n736+   *tstate*, which may be *NULL*.  The global interpreter lock must be held.
711
712
713.. cfunction:: PyObject* PyThreadState_GetDict()
714
715   Return a dictionary in which extensions can store thread-specific state
716   information.  Each extension should use a unique key to use to store state in
717   the dictionary.  It is okay to call this function when no current thread state
718   is available. If this function returns *NULL*, no exception has been raised and
733   zero if the thread id isn't found.  If *exc* is :const:`NULL`, the pending
734   exception (if any) for the thread is cleared. This raises no exceptions.
735
736   .. versionadded:: 2.3
737
738
739.. cfunction:: PyGILState_STATE PyGILState_Ensure()
740
n741-   Ensure that the current thread is ready to call the Python C API regardless of
n767+   Ensure that the current thread is ready to call the Python C API regardless
742-   the current state of Python, or of its thread lock. This may be called as many
768+   of the current state of Python, or of the global interpreter lock. This may
743-   times as desired by a thread as long as each call is matched with a call to
769+   be called as many times as desired by a thread as long as each call is
744-   :cfunc:`PyGILState_Release`. In general, other thread-related APIs may be used
770+   matched with a call to :cfunc:`PyGILState_Release`. In general, other
745-   between :cfunc:`PyGILState_Ensure` and :cfunc:`PyGILState_Release` calls as long
771+   thread-related APIs may be used between :cfunc:`PyGILState_Ensure` and
746-   as the thread state is restored to its previous state before the Release().  For
772+   :cfunc:`PyGILState_Release` calls as long as the thread state is restored to
747-   example, normal usage of the :cmacro:`Py_BEGIN_ALLOW_THREADS` and
773+   its previous state before the Release().  For example, normal usage of the
748-   :cmacro:`Py_END_ALLOW_THREADS` macros is acceptable.
774+   :cmacro:`Py_BEGIN_ALLOW_THREADS` and :cmacro:`Py_END_ALLOW_THREADS` macros is
775+   acceptable.
749
750   The return value is an opaque "handle" to the thread state when
n751-   :cfunc:`PyGILState_Acquire` was called, and must be passed to
n778+   :cfunc:`PyGILState_Ensure` was called, and must be passed to
752   :cfunc:`PyGILState_Release` to ensure Python is left in the same state. Even
753   though recursive calls are allowed, these handles *cannot* be shared - each
n754-   unique call to :cfunc:`PyGILState_Ensure` must save the handle for its call to
n781+   unique call to :cfunc:`PyGILState_Ensure` must save the handle for its call
755-   :cfunc:`PyGILState_Release`.
782+   to :cfunc:`PyGILState_Release`.
756
757   When the function returns, the current thread will hold the GIL. Failure is a
758   fatal error.
759
760   .. versionadded:: 2.3
761
762
763.. cfunction:: void PyGILState_Release(PyGILState_STATE)
886
887
888.. cfunction:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)
889
890   Set the tracing function to *func*.  This is similar to
891   :cfunc:`PyEval_SetProfile`, except the tracing function does receive line-number
892   events.
893
t921+.. cfunction:: PyObject* PyEval_GetCallStats(PyObject *self)
922+ 
923+   Return a tuple of function call counts.  There are constants defined for the
924+   positions within the tuple:
925+ 
926+   +-------------------------------+-------+
927+   | Name                          | Value |
928+   +===============================+=======+
929+   | :const:`PCALL_ALL`            | 0     |
930+   +-------------------------------+-------+
931+   | :const:`PCALL_FUNCTION`       | 1     |
932+   +-------------------------------+-------+
933+   | :const:`PCALL_FAST_FUNCTION`  | 2     |
934+   +-------------------------------+-------+
935+   | :const:`PCALL_FASTER_FUNCTION`| 3     |
936+   +-------------------------------+-------+
937+   | :const:`PCALL_METHOD`         | 4     |
938+   +-------------------------------+-------+
939+   | :const:`PCALL_BOUND_METHOD`   | 5     |
940+   +-------------------------------+-------+
941+   | :const:`PCALL_CFUNCTION`      | 6     |
942+   +-------------------------------+-------+
943+   | :const:`PCALL_TYPE`           | 7     |
944+   +-------------------------------+-------+
945+   | :const:`PCALL_GENERATOR`      | 8     |
946+   +-------------------------------+-------+
947+   | :const:`PCALL_OTHER`          | 9     |
948+   +-------------------------------+-------+
949+   | :const:`PCALL_POP`            | 10    |
950+   +-------------------------------+-------+
951+ 
952+   :const:`PCALL_FAST_FUNCTION` means no argument tuple needs to be created.
953+   :const:`PCALL_FASTER_FUNCTION` means that the fast-path frame setup code is used.
954+ 
955+   If there is a method call where the call can be optimized by changing
956+   the argument tuple and calling the function directly, it gets recorded
957+   twice.
958+ 
959+   This function is only present if Python is compiled with :const:`CALL_PROFILE`
960+   defined.
894
895.. _advanced-debugging:
896
897Advanced Debugger Support
898=========================
899
900.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
901
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op