Guido van Rossum | 46f3e00 | 1992-08-14 09:11:01 +0000 | [diff] [blame] | 1 | \chapter{Data model} |
| 2 | |
| 3 | \section{Objects, values and types} |
| 4 | |
| 5 | {\em Objects} are Python's abstraction for data. All data in a Python |
| 6 | program is represented by objects or by relations between objects. |
| 7 | (In a sense, and in conformance to Von Neumann's model of a |
| 8 | ``stored program computer'', code is also represented by objects.) |
| 9 | \index{object} |
| 10 | \index{data} |
| 11 | |
| 12 | Every object has an identity, a type and a value. An object's {\em |
| 13 | identity} never changes once it has been created; you may think of it |
| 14 | as the object's address in memory. An object's {\em type} is also |
| 15 | unchangeable. It determines the operations that an object supports |
| 16 | (e.g. ``does it have a length?'') and also defines the possible |
| 17 | values for objects of that type. The {\em value} of some objects can |
| 18 | change. Objects whose value can change are said to be {\em mutable}; |
| 19 | objects whose value is unchangeable once they are created are called |
| 20 | {\em immutable}. The type determines an object's (im)mutability. |
| 21 | \index{identity of an object} |
| 22 | \index{value of an object} |
| 23 | \index{type of an object} |
| 24 | \index{mutable object} |
| 25 | \index{immutable object} |
| 26 | |
| 27 | Objects are never explicitly destroyed; however, when they become |
| 28 | unreachable they may be garbage-collected. An implementation is |
| 29 | allowed to delay garbage collection or omit it altogether --- it is a |
| 30 | matter of implementation quality how garbage collection is |
| 31 | implemented, as long as no objects are collected that are still |
| 32 | reachable. (Implementation note: the current implementation uses a |
| 33 | reference-counting scheme which collects most objects as soon as they |
| 34 | become unreachable, but never collects garbage containing circular |
| 35 | references.) |
| 36 | \index{garbage collection} |
| 37 | \index{reference counting} |
| 38 | \index{unreachable object} |
| 39 | |
| 40 | Note that the use of the implementation's tracing or debugging |
| 41 | facilities may keep objects alive that would normally be collectable. |
| 42 | |
| 43 | Some objects contain references to ``external'' resources such as open |
| 44 | files or windows. It is understood that these resources are freed |
| 45 | when the object is garbage-collected, but since garbage collection is |
| 46 | not guaranteed to happen, such objects also provide an explicit way to |
| 47 | release the external resource, usually a \verb\close\ method. |
| 48 | Programs are strongly recommended to always explicitly close such |
| 49 | objects. |
| 50 | |
| 51 | Some objects contain references to other objects; these are called |
| 52 | {\em containers}. Examples of containers are tuples, lists and |
| 53 | dictionaries. The references are part of a container's value. In |
| 54 | most cases, when we talk about the value of a container, we imply the |
| 55 | values, not the identities of the contained objects; however, when we |
| 56 | talk about the (im)mutability of a container, only the identities of |
| 57 | the immediately contained objects are implied. (So, if an immutable |
| 58 | container contains a reference to a mutable object, its value changes |
| 59 | if that mutable object is changed.) |
| 60 | \index{container} |
| 61 | |
| 62 | Types affect almost all aspects of objects' lives. Even the meaning |
| 63 | of object identity is affected in some sense: for immutable types, |
| 64 | operations that compute new values may actually return a reference to |
| 65 | any existing object with the same type and value, while for mutable |
| 66 | objects this is not allowed. E.g. after |
| 67 | |
| 68 | \begin{verbatim} |
| 69 | a = 1; b = 1; c = []; d = [] |
| 70 | \end{verbatim} |
| 71 | |
| 72 | \verb\a\ and \verb\b\ may or may not refer to the same object with the |
| 73 | value one, depending on the implementation, but \verb\c\ and \verb\d\ |
| 74 | are guaranteed to refer to two different, unique, newly created empty |
| 75 | lists. |
| 76 | |
| 77 | \section{The standard type hierarchy} \label{types} |
| 78 | |
| 79 | Below is a list of the types that are built into Python. Extension |
| 80 | modules written in C can define additional types. Future versions of |
| 81 | Python may add types to the type hierarchy (e.g. rational or complex |
| 82 | numbers, efficiently stored arrays of integers, etc.). |
| 83 | \index{type} |
| 84 | \indexii{data}{type} |
| 85 | \indexii{type}{hierarchy} |
| 86 | \indexii{extension}{module} |
| 87 | \index{C} |
| 88 | |
| 89 | Some of the type descriptions below contain a paragraph listing |
| 90 | `special attributes'. These are attributes that provide access to the |
| 91 | implementation and are not intended for general use. Their definition |
| 92 | may change in the future. There are also some `generic' special |
| 93 | attributes, not listed with the individual objects: \verb\__methods__\ |
| 94 | is a list of the method names of a built-in object, if it has any; |
| 95 | \verb\__members__\ is a list of the data attribute names of a built-in |
| 96 | object, if it has any. |
| 97 | \index{attribute} |
| 98 | \indexii{special}{attribute} |
| 99 | \indexiii{generic}{special}{attribute} |
| 100 | \ttindex{__methods__} |
| 101 | \ttindex{__members__} |
| 102 | |
| 103 | \begin{description} |
| 104 | |
| 105 | \item[None] |
| 106 | This type has a single value. There is a single object with this value. |
| 107 | This object is accessed through the built-in name \verb\None\. |
| 108 | It is returned from functions that don't explicitly return an object. |
| 109 | \ttindex{None} |
| 110 | \obindex{None@{\tt None}} |
| 111 | |
| 112 | \item[Numbers] |
| 113 | These are created by numeric literals and returned as results by |
| 114 | arithmetic operators and arithmetic built-in functions. Numeric |
| 115 | objects are immutable; once created their value never changes. Python |
| 116 | numbers are of course strongly related to mathematical numbers, but |
| 117 | subject to the limitations of numerical representation in computers. |
| 118 | \obindex{number} |
| 119 | \obindex{numeric} |
| 120 | |
| 121 | Python distinguishes between integers and floating point numbers: |
| 122 | |
| 123 | \begin{description} |
| 124 | \item[Integers] |
| 125 | These represent elements from the mathematical set of whole numbers. |
| 126 | \obindex{integer} |
| 127 | |
| 128 | There are two types of integers: |
| 129 | |
| 130 | \begin{description} |
| 131 | |
| 132 | \item[Plain integers] |
| 133 | These represent numbers in the range $-2^{31}$ through $2^{31}-1$. |
| 134 | (The range may be larger on machines with a larger natural word |
| 135 | size, but not smaller.) |
| 136 | When the result of an operation falls outside this range, the |
| 137 | exception \verb\OverflowError\ is raised. |
| 138 | For the purpose of shift and mask operations, integers are assumed to |
| 139 | have a binary, 2's complement notation using 32 or more bits, and |
| 140 | hiding no bits from the user (i.e., all $2^{32}$ different bit |
| 141 | patterns correspond to different values). |
| 142 | \obindex{plain integer} |
| 143 | |
| 144 | \item[Long integers] |
| 145 | These represent numbers in an unlimited range, subject to available |
| 146 | (virtual) memory only. For the purpose of shift and mask operations, |
| 147 | a binary representation is assumed, and negative numbers are |
| 148 | represented in a variant of 2's complement which gives the illusion of |
| 149 | an infinite string of sign bits extending to the left. |
| 150 | \obindex{long integer} |
| 151 | |
| 152 | \end{description} % Integers |
| 153 | |
| 154 | The rules for integer representation are intended to give the most |
| 155 | meaningful interpretation of shift and mask operations involving |
| 156 | negative integers and the least surprises when switching between the |
| 157 | plain and long integer domains. For any operation except left shift, |
| 158 | if it yields a result in the plain integer domain without causing |
| 159 | overflow, it will yield the same result in the long integer domain or |
| 160 | when using mixed operands. |
| 161 | \indexii{integer}{representation} |
| 162 | |
| 163 | \item[Floating point numbers] |
| 164 | These represent machine-level double precision floating point numbers. |
| 165 | You are at the mercy of the underlying machine architecture and |
| 166 | C implementation for the accepted range and handling of overflow. |
| 167 | \obindex{floating point} |
| 168 | \indexii{floating point}{number} |
| 169 | \index{C} |
| 170 | |
| 171 | \end{description} % Numbers |
| 172 | |
| 173 | \item[Sequences] |
| 174 | These represent finite ordered sets indexed by natural numbers. |
| 175 | The built-in function \verb\len()\ returns the number of elements |
| 176 | of a sequence. When this number is $n$, the index set contains |
| 177 | the numbers $0, 1, \ldots, n-1$. Element \verb\i\ of sequence |
| 178 | \verb\a\ is selected by \verb\a[i]\. |
| 179 | \obindex{seqence} |
| 180 | \bifuncindex{len} |
| 181 | \index{index operation} |
| 182 | \index{item selection} |
| 183 | \index{subscription} |
| 184 | |
| 185 | Sequences also support slicing: \verb\a[i:j]\ selects all elements |
| 186 | with index $k$ such that $i <= k < j$. When used as an expression, |
| 187 | a slice is a sequence of the same type --- this implies that the |
| 188 | index set is renumbered so that it starts at 0 again. |
| 189 | \index{slicing} |
| 190 | |
| 191 | Sequences are distinguished according to their mutability: |
| 192 | |
| 193 | \begin{description} |
| 194 | % |
| 195 | \item[Immutable sequences] |
| 196 | An object of an immutable sequence type cannot change once it is |
| 197 | created. (If the object contains references to other objects, |
| 198 | these other objects may be mutable and may be changed; however |
| 199 | the collection of objects directly referenced by an immutable object |
| 200 | cannot change.) |
| 201 | \obindex{immutable sequence} |
| 202 | \obindex{immutable} |
| 203 | |
| 204 | The following types are immutable sequences: |
| 205 | |
| 206 | \begin{description} |
| 207 | |
| 208 | \item[Strings] |
| 209 | The elements of a string are characters. There is no separate |
| 210 | character type; a character is represented by a string of one element. |
| 211 | Characters represent (at least) 8-bit bytes. The built-in |
| 212 | functions \verb\chr()\ and \verb\ord()\ convert between characters |
| 213 | and nonnegative integers representing the byte values. |
| 214 | Bytes with the values 0-127 represent the corresponding ASCII values. |
| 215 | The string data type is also used to represent arrays of bytes, e.g. |
| 216 | to hold data read from a file. |
| 217 | \obindex{string} |
| 218 | \index{character} |
| 219 | \index{byte} |
| 220 | \index{ASCII} |
| 221 | \bifuncindex{chr} |
| 222 | \bifuncindex{ord} |
| 223 | |
| 224 | (On systems whose native character set is not ASCII, strings may use |
| 225 | EBCDIC in their internal representation, provided the functions |
| 226 | \verb\chr()\ and \verb\ord()\ implement a mapping between ASCII and |
| 227 | EBCDIC, and string comparison preserves the ASCII order. |
| 228 | Or perhaps someone can propose a better rule?) |
| 229 | \index{ASCII} |
| 230 | \index{EBCDIC} |
| 231 | \index{character set} |
| 232 | \indexii{string}{comparison} |
| 233 | \bifuncindex{chr} |
| 234 | \bifuncindex{ord} |
| 235 | |
| 236 | \item[Tuples] |
| 237 | The elements of a tuple are arbitrary Python objects. |
| 238 | Tuples of two or more elements are formed by comma-separated lists |
| 239 | of expressions. A tuple of one element (a `singleton') can be formed |
| 240 | by affixing a comma to an expression (an expression by itself does |
| 241 | not create a tuple, since parentheses must be usable for grouping of |
| 242 | expressions). An empty tuple can be formed by enclosing `nothing' in |
| 243 | parentheses. |
| 244 | \obindex{tuple} |
| 245 | \indexii{singleton}{tuple} |
| 246 | \indexii{empty}{tuple} |
| 247 | |
| 248 | \end{description} % Immutable sequences |
| 249 | |
| 250 | \item[Mutable sequences] |
| 251 | Mutable sequences can be changed after they are created. The |
| 252 | subscription and slicing notations can be used as the target of |
| 253 | assignment and \verb\del\ (delete) statements. |
| 254 | \obindex{mutable sequece} |
| 255 | \obindex{mutable} |
| 256 | \indexii{assignment}{statement} |
| 257 | \index{delete} |
| 258 | \stindex{del} |
| 259 | \index{subscription} |
| 260 | \index{slicing} |
| 261 | |
| 262 | There is currently a single mutable sequence type: |
| 263 | |
| 264 | \begin{description} |
| 265 | |
| 266 | \item[Lists] |
| 267 | The elements of a list are arbitrary Python objects. Lists are formed |
| 268 | by placing a comma-separated list of expressions in square brackets. |
| 269 | (Note that there are no special cases needed to form lists of length 0 |
| 270 | or 1.) |
| 271 | \obindex{list} |
| 272 | |
| 273 | \end{description} % Mutable sequences |
| 274 | |
| 275 | \end{description} % Sequences |
| 276 | |
| 277 | \item[Mapping types] |
| 278 | These represent finite sets of objects indexed by arbitrary index sets. |
| 279 | The subscript notation \verb\a[k]\ selects the element indexed |
| 280 | by \verb\k\ from the mapping \verb\a\; this can be used in |
| 281 | expressions and as the target of assignments or \verb\del\ statements. |
| 282 | The built-in function \verb\len()\ returns the number of elements |
| 283 | in a mapping. |
| 284 | \bifuncindex{len} |
| 285 | \index{subscription} |
| 286 | \obindex{mapping} |
| 287 | |
| 288 | There is currently a single mapping type: |
| 289 | |
| 290 | \begin{description} |
| 291 | |
| 292 | \item[Dictionaries] |
| 293 | These represent finite sets of objects indexed by strings. |
| 294 | Dictionaries are mutable; they are created by the \verb\{...}\ |
| 295 | notation (see section \ref{dict}). (Implementation note: the strings |
| 296 | used for indexing must not contain null bytes.) |
| 297 | \obindex{dictionary} |
| 298 | \obindex{mutable} |
| 299 | |
| 300 | \end{description} % Mapping types |
| 301 | |
| 302 | \item[Callable types] |
| 303 | These are the types to which the function call (invocation) operation, |
| 304 | written as \verb\function(argument, argument, ...)\, can be applied: |
| 305 | \indexii{function}{call} |
| 306 | \index{invocation} |
| 307 | \indexii{function}{argument} |
| 308 | \obindex{callable} |
| 309 | |
| 310 | \begin{description} |
| 311 | |
| 312 | \item[User-defined functions] |
| 313 | A user-defined function object is created by a function definition |
| 314 | (see section \ref{function}). It should be called with an argument |
| 315 | list containing the same number of items as the function's formal |
| 316 | parameter list. |
| 317 | \indexii{user-defined}{function} |
| 318 | \obindex{function} |
| 319 | \obindex{user-defined function} |
| 320 | |
| 321 | Special read-only attributes: \verb\func_code\ is the code object |
| 322 | representing the compiled function body, and \verb\func_globals\ is (a |
| 323 | reference to) the dictionary that holds the function's global |
| 324 | variables --- it implements the global name space of the module in |
| 325 | which the function was defined. |
| 326 | \ttindex{func_code} |
| 327 | \ttindex{func_globals} |
| 328 | \indexii{global}{name space} |
| 329 | |
| 330 | \item[User-defined methods] |
| 331 | A user-defined method (a.k.a. {\em object closure}) is a pair of a |
| 332 | class instance object and a user-defined function. It should be |
| 333 | called with an argument list containing one item less than the number |
| 334 | of items in the function's formal parameter list. When called, the |
| 335 | class instance becomes the first argument, and the call arguments are |
| 336 | shifted one to the right. |
| 337 | \obindex{method} |
| 338 | \obindex{user-defined method} |
| 339 | \indexii{user-defined}{method} |
| 340 | \index{object closure} |
| 341 | |
| 342 | Special read-only attributes: \verb\im_self\ is the class instance |
| 343 | object, \verb\im_func\ is the function object. |
| 344 | \ttindex{im_func} |
| 345 | \ttindex{im_self} |
| 346 | |
| 347 | \item[Built-in functions] |
| 348 | A built-in function object is a wrapper around a C function. Examples |
| 349 | of built-in functions are \verb\len\ and \verb\math.sin\. There |
| 350 | are no special attributes. The number and type of the arguments are |
| 351 | determined by the C function. |
| 352 | \obindex{built-in function} |
| 353 | \obindex{function} |
| 354 | \index{C} |
| 355 | |
| 356 | \item[Built-in methods] |
| 357 | This is really a different disguise of a built-in function, this time |
| 358 | containing an object passed to the C function as an implicit extra |
| 359 | argument. An example of a built-in method is \verb\list.append\ if |
| 360 | \verb\list\ is a list object. |
| 361 | \obindex{built-in method} |
| 362 | \obindex{method} |
| 363 | \indexii{built-in}{method} |
| 364 | |
| 365 | \item[Classes] |
| 366 | Class objects are described below. When a class object is called as a |
| 367 | parameterless function, a new class instance (also described below) is |
| 368 | created and returned. The class's initialization function is not |
| 369 | called --- this is the responsibility of the caller. It is illegal to |
| 370 | call a class object with one or more arguments. |
| 371 | \obindex{class} |
| 372 | \obindex{class instance} |
| 373 | \obindex{instance} |
| 374 | \indexii{class object}{call} |
| 375 | |
| 376 | \end{description} |
| 377 | |
| 378 | \item[Modules] |
| 379 | Modules are imported by the \verb\import\ statement (see section |
| 380 | \ref{import}). A module object is a container for a module's name |
| 381 | space, which is a dictionary (the same dictionary as referenced by the |
| 382 | \verb\func_globals\ attribute of functions defined in the module). |
| 383 | Module attribute references are translated to lookups in this |
| 384 | dictionary. A module object does not contain the code object used to |
| 385 | initialize the module (since it isn't needed once the initialization |
| 386 | is done). |
| 387 | \stindex{import} |
| 388 | \obindex{module} |
| 389 | |
| 390 | Attribute assignment update the module's name space dictionary. |
| 391 | |
| 392 | Special read-only attributes: \verb\__dict__\ yields the module's name |
| 393 | space as a dictionary object; \verb\__name__\ yields the module's name |
| 394 | as a string object. |
| 395 | \ttindex{__dict__} |
| 396 | \ttindex{__name__} |
| 397 | \indexii{module}{name space} |
| 398 | |
| 399 | \item[Classes] |
| 400 | Class objects are created by class definitions (see section |
| 401 | \ref{class}). A class is a container for a dictionary containing the |
| 402 | class's name space. Class attribute references are translated to |
| 403 | lookups in this dictionary. When an attribute name is not found |
| 404 | there, the attribute search continues in the base classes. The search |
| 405 | is depth-first, left-to-right in the order of their occurrence in the |
| 406 | base class list. |
| 407 | \obindex{class} |
| 408 | \obindex{class instance} |
| 409 | \obindex{instance} |
| 410 | \indexii{class object}{call} |
| 411 | \index{container} |
| 412 | \index{dictionary} |
| 413 | \indexii{class}{attribute} |
| 414 | |
| 415 | Class attribute assignments update the class's dictionary, never the |
| 416 | dictionary of a base class. |
| 417 | \indexiii{class}{attribute}{assignment} |
| 418 | |
| 419 | A class can be called as a parameterless function to yield a class |
| 420 | instance (see above). |
| 421 | \indexii{class object}{call} |
| 422 | |
| 423 | Special read-only attributes: \verb\__dict__\ yields the dictionary |
| 424 | containing the class's name space; \verb\__bases__\ yields a tuple |
| 425 | (possibly empty or a singleton) containing the base classes, in the |
| 426 | order of their occurrence in the base class list. |
| 427 | \ttindex{__dict__} |
| 428 | \ttindex{__bases__} |
| 429 | |
| 430 | \item[Class instances] |
| 431 | A class instance is created by calling a class object as a |
| 432 | parameterless function. A class instance has a dictionary in which |
| 433 | attribute references are searched. When an attribute is not found |
| 434 | there, and the instance's class has an attribute by that name, and |
| 435 | that class attribute is a user-defined function (and in no other |
| 436 | cases), the instance attribute reference yields a user-defined method |
| 437 | object (see above) constructed from the instance and the function. |
| 438 | \obindex{class instance} |
| 439 | \obindex{instance} |
| 440 | \indexii{class}{instance} |
| 441 | \indexii{class instance}{attribute} |
| 442 | |
| 443 | Attribute assignments update the instance's dictionary. |
| 444 | \indexiii{class instance}{attribute}{assignment} |
| 445 | |
| 446 | Class instances can pretend to be numbers, sequences, or mappings if |
| 447 | they have methods with certain special names. These are described in |
| 448 | section \ref{specialnames}. |
| 449 | \obindex{number} |
| 450 | \obindex{sequence} |
| 451 | \obindex{mapping} |
| 452 | |
| 453 | Special read-only attributes: \verb\__dict__\ yields the attribute |
| 454 | dictionary; \verb\__class__\ yields the instance's class. |
| 455 | \ttindex{__dict__} |
| 456 | \ttindex{__class__} |
| 457 | |
| 458 | \item[Files] |
| 459 | A file object represents an open file. (It is a wrapper around a C |
| 460 | {\tt stdio} file pointer.) File objects are created by the |
| 461 | \verb\open()\ built-in function, and also by \verb\posix.popen()\ and |
| 462 | the \verb\makefile\ method of socket objects. \verb\sys.stdin\, |
| 463 | \verb\sys.stdout\ and \verb\sys.stderr\ are file objects corresponding |
| 464 | the the interpreter's standard input, output and error streams. |
| 465 | See the Python Library Reference for methods of file objects and other |
| 466 | details. |
| 467 | \obindex{file} |
| 468 | \index{C} |
| 469 | \index{stdio} |
| 470 | \bifuncindex{open} |
| 471 | \bifuncindex{popen} |
| 472 | \bifuncindex{makefile} |
| 473 | \ttindex{stdin} |
| 474 | \ttindex{stdout} |
| 475 | \ttindex{stderr} |
| 476 | \ttindex{sys.stdin} |
| 477 | \ttindex{sys.stdout} |
| 478 | \ttindex{sys.stderr} |
| 479 | |
| 480 | \item[Internal types] |
| 481 | A few types used internally by the interpreter are exposed to the user. |
| 482 | Their definition may change with future versions of the interpreter, |
| 483 | but they are mentioned here for completeness. |
| 484 | \index{internal type} |
| 485 | |
| 486 | \begin{description} |
| 487 | |
| 488 | \item[Code objects] |
| 489 | Code objects represent executable code. The difference between a code |
| 490 | object and a function object is that the function object contains an |
| 491 | explicit reference to the function's context (the module in which it |
| 492 | was defined) which a code object contains no context. There is no way |
| 493 | to execute a bare code object. |
| 494 | \obindex{code} |
| 495 | |
| 496 | Special read-only attributes: \verb\co_code\ is a string representing |
| 497 | the sequence of instructions; \verb\co_consts\ is a list of literals |
| 498 | used by the code; \verb\co_names\ is a list of names (strings) used by |
| 499 | the code; \verb\co_filename\ is the filename from which the code was |
| 500 | compiled. (To find out the line numbers, you would have to decode the |
| 501 | instructions; the standard library module \verb\dis\ contains an |
| 502 | example of how to do this.) |
| 503 | \ttindex{co_code} |
| 504 | \ttindex{co_consts} |
| 505 | \ttindex{co_names} |
| 506 | \ttindex{co_filename} |
| 507 | |
| 508 | \item[Frame objects] |
| 509 | Frame objects represent execution frames. They may occur in traceback |
| 510 | objects (see below). |
| 511 | \obindex{frame} |
| 512 | |
| 513 | Special read-only attributes: \verb\f_back\ is to the previous |
| 514 | stack frame (towards the caller), or \verb\None\ if this is the bottom |
| 515 | stack frame; \verb\f_code\ is the code object being executed in this |
| 516 | frame; \verb\f_globals\ is the dictionary used to look up global |
| 517 | variables; \verb\f_locals\ is used for local variables; |
| 518 | \verb\f_lineno\ gives the line number and \verb\f_lasti\ gives the |
| 519 | precise instruction (this is an index into the instruction string of |
| 520 | the code object). |
| 521 | \ttindex{f_back} |
| 522 | \ttindex{f_code} |
| 523 | \ttindex{f_globals} |
| 524 | \ttindex{f_locals} |
| 525 | \ttindex{f_lineno} |
| 526 | \ttindex{f_lasti} |
| 527 | |
| 528 | \item[Traceback objects] |
| 529 | Traceback objects represent a stack trace of an exception. A |
| 530 | traceback object is created when an exception occurs. When the search |
| 531 | for an exception handler unwinds the execution stack, at each unwound |
| 532 | level a traceback object is inserted in front of the current |
| 533 | traceback. When an exception handler is entered, the stack trace is |
| 534 | made available to the program as \verb\sys.exc_traceback\. When the |
| 535 | program contains no suitable handler, the stack trace is written |
| 536 | (nicely formatted) to the standard error stream; if the interpreter is |
| 537 | interactive, it is also made available to the user as |
| 538 | \verb\sys.last_traceback\. |
| 539 | \obindex{traceback} |
| 540 | \indexii{stack}{trace} |
| 541 | \indexii{exception}{handler} |
| 542 | \indexii{execution}{stack} |
| 543 | \ttindex{exc_traceback} |
| 544 | \ttindex{last_traceback} |
| 545 | \ttindex{sys.exc_traceback} |
| 546 | \ttindex{sys.last_traceback} |
| 547 | |
| 548 | Special read-only attributes: \verb\tb_next\ is the next level in the |
| 549 | stack trace (towards the frame where the exception occurred), or |
| 550 | \verb\None\ if there is no next level; \verb\tb_frame\ points to the |
| 551 | execution frame of the current level; \verb\tb_lineno\ gives the line |
| 552 | number where the exception occurred; \verb\tb_lasti\ indicates the |
| 553 | precise instruction. The line number and last instruction in the |
| 554 | traceback may differ from the line number of its frame object if the |
| 555 | exception occurred in a \verb\try\ statement with no matching |
| 556 | \verb\except\ clause or with a \verb\finally\ clause. |
| 557 | \ttindex{tb_next} |
| 558 | \ttindex{tb_frame} |
| 559 | \ttindex{tb_lineno} |
| 560 | \ttindex{tb_lasti} |
| 561 | \stindex{try} |
| 562 | |
| 563 | \end{description} % Internal types |
| 564 | |
| 565 | \end{description} % Types |
| 566 | |
| 567 | |
| 568 | \section{Special method names} \label{specialnames} |
| 569 | |
| 570 | A class can implement certain operations that are invoked by special |
| 571 | syntax (such as subscription or arithmetic operations) by defining |
| 572 | methods with special names. For instance, if a class defines a |
| 573 | method named \verb\__getitem__\, and \verb\x\ is an instance of this |
| 574 | class, then \verb\x[i]\ is equivalent to \verb\x.__getitem__(i)\. |
| 575 | (The reverse is not true --- if \verb\x\ is a list object, |
| 576 | \verb\x.__getitem__(i)\ is not equivalent to \verb\x[i]\.) |
| 577 | |
| 578 | Except for \verb\__repr__\ and \verb\__cmp__\, attempts to execute an |
| 579 | operation raise an exception when no appropriate method is defined. |
| 580 | For \verb\__repr__\ and \verb\__cmp__\, the traditional |
| 581 | interpretations are used in this case. |
| 582 | |
| 583 | |
| 584 | \subsection{Special methods for any type} |
| 585 | |
| 586 | \begin{description} |
| 587 | |
| 588 | \item[\tt __repr__(self)] |
| 589 | Called by the \verb\print\ statement and conversions (reverse quotes) to |
| 590 | compute the string representation of an object. |
| 591 | |
| 592 | \item[\tt _cmp__(self, other)] |
| 593 | Called by all comparison operations. Should return -1 if |
| 594 | \verb\self < other\, 0 if \verb\self == other\, +1 if |
| 595 | \verb\self > other\. (Implementation note: due to limitations in the |
| 596 | interpreter, exceptions raised by comparisons are ignored, and the |
| 597 | objects will be considered equal in this case.) |
| 598 | |
| 599 | \end{description} |
| 600 | |
| 601 | |
| 602 | \subsection{Special methods for sequence and mapping types} |
| 603 | |
| 604 | \begin{description} |
| 605 | |
| 606 | \item[\tt __len__(self)] |
| 607 | Called to implement the built-in function \verb\len()\. Should return |
| 608 | the length of the object, an integer \verb\>=\ 0. Also, an object |
| 609 | whose \verb\__len__()\ method returns 0 is considered to be false in a |
| 610 | Boolean context. |
| 611 | |
| 612 | \item[\tt __getitem__(self, key)] |
| 613 | Called to implement evaluation of \verb\self[key]\. Note that the |
| 614 | special interpretation of negative keys (if the class wishes to |
| 615 | emulate a sequence type) is up to the \verb\__getitem__\ method. |
| 616 | |
| 617 | \item[\tt __setitem__(self, key, value)] |
| 618 | Called to implement assignment to \verb\self[key]\. Same note as for |
| 619 | \verb\__getitem__\. |
| 620 | |
| 621 | \item[\tt __delitem__(self, key)] |
| 622 | Called to implement deletion of \verb\self[key]\. Same note as for |
| 623 | \verb\__getitem__\. |
| 624 | |
| 625 | \end{description} |
| 626 | |
| 627 | |
| 628 | \subsection{Special methods for sequence types} |
| 629 | |
| 630 | \begin{description} |
| 631 | |
| 632 | \item[\tt __getslice__(self, i, j)] |
| 633 | Called to implement evaluation of \verb\self[i:j]\. Note that missing |
| 634 | \verb\i\ or \verb\j\ are replaced by 0 or \verb\len(self)\, |
| 635 | respectively, and \verb\len(self)\ has been added (once) to originally |
| 636 | negative \verb\i\ or \verb\j\ by the time this function is called |
| 637 | (unlike for \verb\__getitem__\). |
| 638 | |
| 639 | \item[\tt __setslice__(self, i, j, sequence)] |
| 640 | Called to implement assignment to \verb\self[i:j]\. Same notes as for |
| 641 | \verb\__getslice__\. |
| 642 | |
| 643 | \item[\tt __delslice__(self, i, j)] |
| 644 | Called to implement deletion of \verb\self[i:j]\. Same notes as for |
| 645 | \verb\__getslice__\. |
| 646 | |
| 647 | \end{description} |
| 648 | |
| 649 | |
| 650 | \subsection{Special methods for numeric types} |
| 651 | |
| 652 | \begin{description} |
| 653 | |
| 654 | \item[\tt __add__(self, other)]\itemjoin |
| 655 | \item[\tt __sub__(self, other)]\itemjoin |
| 656 | \item[\tt __mul__(self, other)]\itemjoin |
| 657 | \item[\tt __div__(self, other)]\itemjoin |
| 658 | \item[\tt __mod__(self, other)]\itemjoin |
| 659 | \item[\tt __divmod__(self, other)]\itemjoin |
| 660 | \item[\tt __pow__(self, other)]\itemjoin |
| 661 | \item[\tt __lshift__(self, other)]\itemjoin |
| 662 | \item[\tt __rshift__(self, other)]\itemjoin |
| 663 | \item[\tt __and__(self, other)]\itemjoin |
| 664 | \item[\tt __xor__(self, other)]\itemjoin |
| 665 | \item[\tt __or__(self, other)]\itembreak |
| 666 | Called to implement the binary arithmetic operations (\verb\+\, |
| 667 | \verb\-\, \verb\*\, \verb\/\, \verb\%\, \verb\divmod()\, \verb\pow()\, |
| 668 | \verb\<<\, \verb\>>\, \verb\&\, \verb\^\, \verb\|\). |
| 669 | |
| 670 | \item[\tt __neg__(self)]\itemjoin |
| 671 | \item[\tt __pos__(self)]\itemjoin |
| 672 | \item[\tt __abs__(self)]\itemjoin |
| 673 | \item[\tt __invert__(self)]\itembreak |
| 674 | Called to implement the unary arithmetic operations (\verb\-\, \verb\+\, |
| 675 | \verb\abs()\ and \verb\~\). |
| 676 | |
| 677 | \item[\tt __nonzero__(self)] |
| 678 | Called to implement boolean testing; should return 0 or 1. An |
| 679 | alternative name for this method is \verb\__len__\. |
| 680 | |
| 681 | \item[\tt __coerce__(self, other)] |
| 682 | Called to implement ``mixed-mode'' numeric arithmetic. Should either |
| 683 | return a tuple containing self and other converted to a common numeric |
| 684 | type, or None if no way of conversion is known. When the common type |
| 685 | would be the type of other, it is sufficient to return None, since the |
| 686 | interpreter will also ask the other object to attempt a coercion (but |
| 687 | sometimes, if the implementation of the other type cannot be changed, |
| 688 | it is useful to do the conversion to the other type here). |
| 689 | |
| 690 | Note that this method is not called to coerce the arguments to \verb\+\ |
| 691 | and \verb\*\, because these are also used to implement sequence |
| 692 | concatenation and repetition, respectively. Also note that, for the |
| 693 | same reason, in \verb\n*x\, where \verb\n\ is a built-in number and |
| 694 | \verb\x\ is an instance, a call to \verb\x.__mul__(n)\ is made.% |
| 695 | \footnote{The interpreter should really distinguish between |
| 696 | user-defined classes implementing sequences, mappings or numbers, but |
| 697 | currently it doesn't --- hence this strange exception.} |
| 698 | |
| 699 | \item[\tt __int__(self)]\itemjoin |
| 700 | \item[\tt __long__(self)]\itemjoin |
| 701 | \item[\tt __float__(self)]\itembreak |
| 702 | Called to implement the built-in functions \verb\int()\, \verb\long()\ |
| 703 | and \verb\float()\. Should return a value of the appropriate type. |
| 704 | |
Guido van Rossum | 66122d2 | 1992-09-20 21:43:47 +0000 | [diff] [blame] | 705 | \item[\tt __oct__(self)]\itemjoin |
| 706 | \item[\tt __hex__(self)]\itembreak |
| 707 | Called to implement the built-in functions \verb\oct()\ and |
| 708 | \verb\hex()\. Should return a string value. |
| 709 | |
Guido van Rossum | 46f3e00 | 1992-08-14 09:11:01 +0000 | [diff] [blame] | 710 | \end{description} |