If it contains references to other objects, their reference count is decremented. Those other objects may be deallocated in turn, if this decrement makes their reference count become zero, and so on.
Reference counts are always manipulated explicitly. Thus, the reference count increment is a simple operation. The only real reason to use the reference count is to prevent the object from being deallocated as long as our variable is pointing to it.
If we know that there is at least one other reference to the object that lives at least as long as our variable, there is no need to increment the reference count temporarily. An important situation where this arises is in objects that are passed as arguments to C functions in an extension module that are called from Python; the call mechanism guarantees to hold a reference to every argument for the duration of the call.
However, a common pitfall is to extract an object from a list and hold on to it for a while without incrementing its reference count. Some other operation might conceivably remove the object from the list, decrementing its reference count and possibly deallocating it.
These operations always increment the reference count of the object they return. Ownership pertains to references, never to objects objects are not owned: they are always shared.
When a function passes ownership of a reference on to its caller, the caller is said to receive a new reference. When no ownership is transferred, the caller is said to borrow the reference. Nothing needs to be done for a borrowed reference. Conversely, when a calling function passes in a reference to an object, there are two possibilities: the function steals a reference to the object, or it does not. Stealing a reference means that when you pass a reference to a function, that function assumes that it now owns that reference, and you are not responsible for it any longer.
These functions were designed to steal a reference because of a common idiom for populating a tuple or list with newly created objects; for example, the code to create the tuple 1, 2, "three" could look like this forgetting about error handling for the moment; a better way to code this is shown below :.
However, in practice, you will rarely use these ways of creating and populating a tuple or list. For example, the above two blocks of code could be replaced by the following which also takes care of the error checking :.
For example, this function sets all items of a list actually, any mutable sequence to a given item:. The situation is slightly different for function return values. While passing a reference to most functions does not change your ownership responsibilities for that reference, many functions that return a reference to an object give you ownership of the reference.
The reason is simple: in many cases, the returned object is created on the fly, and the reference you get is the only reference to the object. A few structure types are used to describe static tables used to list the functions exported by a module or the data attributes of a new object type, and another is used to describe the value of a complex number.
These will be discussed together with the functions that use them. For C programmers, however, error checking always has to be explicit. In general, when a function encounters an error, it sets an exception, discards any object references that it owns, and returns an error indicator. These exceptions are always explicitly documented. Exception state is maintained in per-thread storage this is equivalent to using global storage in an unthreaded application.
A thread can be in one of two states: an exception has occurred, or not. The full exception state consists of three objects all of which can be NULL : the exception type, the corresponding exception value, and the traceback.
These have the same meanings as the Python result of sys. Note that starting with Python 1. This prevents common bugs in exception handling code caused by an innocent-looking function overwriting the exception being handled; it also reduces the often unwanted lifetime extension for objects that are referenced by the stack frames in the traceback. As a general principle, a function that calls another function to perform some task should check whether the called function raised an exception, and if so, pass the exception state on to its caller.
It should discard any object references that it owns, and return an error indicator, but it should not set another exception — that would overwrite the exception that was just raised, and lose important information about the exact cause of the error. The following example function shows some error cleanup. First, to remind you why you like Python, we show the equivalent Python code:.
This example represents an endorsed use of the goto statement in C! It is important that the variables used to hold owned references are initialized to NULL for this to work; likewise, the proposed return value is initialized to -1 failure and only set to success after the final call made is successful.
The one important task that only embedders as opposed to extension writers of the Python interpreter have to worry about is the initialization, and possibly the finalization, of the Python interpreter. Most functionality of the interpreter can only be used after the interpreter has been initialized.
It also initializes the module search path sys. Y relative to the parent directory where the executable named python is found on the shell command search path the environment variable PATH. More information about these functions is given in a later chapter. Python can be built with several macros to enable extra checks of the interpreter and extension modules.
These checks tend to add a large amount of overhead to the runtime so they are not enabled by default. Builds are available that support tracing of reference counts, debugging the memory allocator, or low-level profiling of the main interpreter loop.
Only the most frequently-used builds will be described in the remainder of this section. In addition to the reference count debugging described below, extra checks are performed, see Python Debug Build. When defined, a circular doubly linked list of active objects is maintained by adding two extra fields to every PyObject.
Alternate Implementations 1. Notation 2. Lexical analysis 2. Line structure 2. Other tokens 2. Identifiers and keywords 2. Literals 2. Operators 2. Delimiters 3. Data model 3. Objects, values and types 3. The standard type hierarchy 3. Special method names 3. Coroutines 4. Execution model 4. Structure of a program 4. Naming and binding 4. Exceptions 5. The import system 5. Packages 5. Searching 5. Loading 5. The Path Based Finder 5.
Replacing the standard import system 5. Package Relative Imports 5. Open issues 5. References 6. Expressions 6. Arithmetic conversions 6. Atoms 6. Primaries 6. Await expression 6. The power operator 6. Unary arithmetic and bitwise operations 6. Binary arithmetic operations 6. Shifting operations 6. Binary bitwise operations 6. Comparisons 6. Boolean operations 6.
Assignment expressions 6. Conditional expressions 6. Lambdas 6. Expression lists 6. Evaluation order 6.
0コメント