Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 | |
| 2 | .. _built-in-funcs: |
| 3 | |
| 4 | Built-in Functions |
| 5 | ================== |
| 6 | |
| 7 | The Python interpreter has a number of functions built into it that are always |
| 8 | available. They are listed here in alphabetical order. |
| 9 | |
| 10 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 11 | .. function:: abs(x) |
| 12 | |
| 13 | Return the absolute value of a number. The argument may be a plain or long |
| 14 | integer or a floating point number. If the argument is a complex number, its |
| 15 | magnitude is returned. |
| 16 | |
| 17 | |
| 18 | .. function:: all(iterable) |
| 19 | |
Raymond Hettinger | 76162e3 | 2009-04-16 18:16:10 +0000 | [diff] [blame] | 20 | Return True if all elements of the *iterable* are true (or if the iterable |
| 21 | is empty). Equivalent to:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 22 | |
| 23 | def all(iterable): |
| 24 | for element in iterable: |
| 25 | if not element: |
| 26 | return False |
| 27 | return True |
| 28 | |
| 29 | .. versionadded:: 2.5 |
| 30 | |
| 31 | |
| 32 | .. function:: any(iterable) |
| 33 | |
Raymond Hettinger | 76162e3 | 2009-04-16 18:16:10 +0000 | [diff] [blame] | 34 | Return True if any element of the *iterable* is true. If the iterable |
| 35 | is empty, return False. Equivalent to:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 36 | |
| 37 | def any(iterable): |
| 38 | for element in iterable: |
| 39 | if element: |
| 40 | return True |
| 41 | return False |
| 42 | |
| 43 | .. versionadded:: 2.5 |
| 44 | |
| 45 | |
| 46 | .. function:: basestring() |
| 47 | |
| 48 | This abstract type is the superclass for :class:`str` and :class:`unicode`. It |
| 49 | cannot be called or instantiated, but it can be used to test whether an object |
| 50 | is an instance of :class:`str` or :class:`unicode`. ``isinstance(obj, |
| 51 | basestring)`` is equivalent to ``isinstance(obj, (str, unicode))``. |
| 52 | |
| 53 | .. versionadded:: 2.3 |
| 54 | |
| 55 | |
Benjamin Peterson | b5f8208 | 2008-10-30 22:39:25 +0000 | [diff] [blame] | 56 | .. function:: bin(x) |
| 57 | |
| 58 | Convert an integer number to a binary string. The result is a valid Python |
| 59 | expression. If *x* is not a Python :class:`int` object, it has to define an |
| 60 | :meth:`__index__` method that returns an integer. |
| 61 | |
| 62 | .. versionadded:: 2.6 |
| 63 | |
| 64 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 65 | .. function:: bool([x]) |
| 66 | |
| 67 | Convert a value to a Boolean, using the standard truth testing procedure. If |
| 68 | *x* is false or omitted, this returns :const:`False`; otherwise it returns |
| 69 | :const:`True`. :class:`bool` is also a class, which is a subclass of |
| 70 | :class:`int`. Class :class:`bool` cannot be subclassed further. Its only |
| 71 | instances are :const:`False` and :const:`True`. |
| 72 | |
| 73 | .. index:: pair: Boolean; type |
| 74 | |
| 75 | .. versionadded:: 2.2.1 |
| 76 | |
| 77 | .. versionchanged:: 2.3 |
| 78 | If no argument is given, this function returns :const:`False`. |
| 79 | |
| 80 | |
| 81 | .. function:: callable(object) |
| 82 | |
| 83 | Return :const:`True` if the *object* argument appears callable, |
| 84 | :const:`False` if not. If this |
| 85 | returns true, it is still possible that a call fails, but if it is false, |
| 86 | calling *object* will never succeed. Note that classes are callable (calling a |
| 87 | class returns a new instance); class instances are callable if they have a |
| 88 | :meth:`__call__` method. |
| 89 | |
| 90 | |
| 91 | .. function:: chr(i) |
| 92 | |
| 93 | Return a string of one character whose ASCII code is the integer *i*. For |
| 94 | example, ``chr(97)`` returns the string ``'a'``. This is the inverse of |
| 95 | :func:`ord`. The argument must be in the range [0..255], inclusive; |
| 96 | :exc:`ValueError` will be raised if *i* is outside that range. See |
| 97 | also :func:`unichr`. |
| 98 | |
| 99 | |
| 100 | .. function:: classmethod(function) |
| 101 | |
| 102 | Return a class method for *function*. |
| 103 | |
| 104 | A class method receives the class as implicit first argument, just like an |
| 105 | instance method receives the instance. To declare a class method, use this |
| 106 | idiom:: |
| 107 | |
| 108 | class C: |
| 109 | @classmethod |
| 110 | def f(cls, arg1, arg2, ...): ... |
| 111 | |
Georg Brandl | 584265b | 2007-12-02 14:58:50 +0000 | [diff] [blame] | 112 | The ``@classmethod`` form is a function :term:`decorator` -- see the description |
| 113 | of function definitions in :ref:`function` for details. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 114 | |
| 115 | It can be called either on the class (such as ``C.f()``) or on an instance (such |
| 116 | as ``C().f()``). The instance is ignored except for its class. If a class |
| 117 | method is called for a derived class, the derived class object is passed as the |
| 118 | implied first argument. |
| 119 | |
| 120 | Class methods are different than C++ or Java static methods. If you want those, |
| 121 | see :func:`staticmethod` in this section. |
| 122 | |
| 123 | For more information on class methods, consult the documentation on the standard |
| 124 | type hierarchy in :ref:`types`. |
| 125 | |
| 126 | .. versionadded:: 2.2 |
| 127 | |
| 128 | .. versionchanged:: 2.4 |
| 129 | Function decorator syntax added. |
| 130 | |
| 131 | |
| 132 | .. function:: cmp(x, y) |
| 133 | |
| 134 | Compare the two objects *x* and *y* and return an integer according to the |
| 135 | outcome. The return value is negative if ``x < y``, zero if ``x == y`` and |
| 136 | strictly positive if ``x > y``. |
| 137 | |
| 138 | |
| 139 | .. function:: compile(source, filename, mode[, flags[, dont_inherit]]) |
| 140 | |
Georg Brandl | fc8eef3 | 2008-03-28 12:11:56 +0000 | [diff] [blame] | 141 | Compile the *source* into a code or AST object. Code objects can be executed |
| 142 | by an :keyword:`exec` statement or evaluated by a call to :func:`eval`. |
Benjamin Peterson | d923f98 | 2008-11-08 16:55:33 +0000 | [diff] [blame] | 143 | *source* can either be a string or an AST object. Refer to the :mod:`ast` |
| 144 | module documentation for information on how to work with AST objects. |
Georg Brandl | fc8eef3 | 2008-03-28 12:11:56 +0000 | [diff] [blame] | 145 | |
| 146 | The *filename* argument should give the file from which the code was read; |
| 147 | pass some recognizable value if it wasn't read from a file (``'<string>'`` is |
| 148 | commonly used). |
| 149 | |
| 150 | The *mode* argument specifies what kind of code must be compiled; it can be |
| 151 | ``'exec'`` if *source* consists of a sequence of statements, ``'eval'`` if it |
| 152 | consists of a single expression, or ``'single'`` if it consists of a single |
| 153 | interactive statement (in the latter case, expression statements that |
R. David Murray | 4ee6d25 | 2009-06-22 22:11:04 +0000 | [diff] [blame] | 154 | evaluate to something other than ``None`` will be printed). |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 155 | |
Benjamin Peterson | 728c6f6 | 2008-11-08 17:04:18 +0000 | [diff] [blame] | 156 | The optional arguments *flags* and *dont_inherit* control which future |
| 157 | statements (see :pep:`236`) affect the compilation of *source*. If neither |
| 158 | is present (or both are zero) the code is compiled with those future |
| 159 | statements that are in effect in the code that is calling compile. If the |
| 160 | *flags* argument is given and *dont_inherit* is not (or is zero) then the |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 161 | future statements specified by the *flags* argument are used in addition to |
| 162 | those that would be used anyway. If *dont_inherit* is a non-zero integer then |
Benjamin Peterson | 728c6f6 | 2008-11-08 17:04:18 +0000 | [diff] [blame] | 163 | the *flags* argument is it -- the future statements in effect around the call |
| 164 | to compile are ignored. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 165 | |
Georg Brandl | f725b95 | 2008-01-05 19:44:22 +0000 | [diff] [blame] | 166 | Future statements are specified by bits which can be bitwise ORed together to |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 167 | specify multiple statements. The bitfield required to specify a given feature |
| 168 | can be found as the :attr:`compiler_flag` attribute on the :class:`_Feature` |
| 169 | instance in the :mod:`__future__` module. |
| 170 | |
Georg Brandl | 516787d | 2008-01-06 16:22:56 +0000 | [diff] [blame] | 171 | This function raises :exc:`SyntaxError` if the compiled source is invalid, |
| 172 | and :exc:`TypeError` if the source contains null bytes. |
| 173 | |
Benjamin Peterson | d923f98 | 2008-11-08 16:55:33 +0000 | [diff] [blame] | 174 | .. note:: |
| 175 | |
Georg Brandl | b6fb8dc | 2009-11-14 11:50:51 +0000 | [diff] [blame] | 176 | When compiling a string with multi-line code in ``'single'`` or |
Benjamin Peterson | 2fb77bd | 2009-11-13 22:56:00 +0000 | [diff] [blame] | 177 | ``'eval'`` mode, input must be terminated by at least one newline |
| 178 | character. This is to facilitate detection of incomplete and complete |
| 179 | statements in the :mod:`code` module. |
Benjamin Peterson | d923f98 | 2008-11-08 16:55:33 +0000 | [diff] [blame] | 180 | |
Benjamin Peterson | 728c6f6 | 2008-11-08 17:04:18 +0000 | [diff] [blame] | 181 | .. versionchanged:: 2.3 |
Benjamin Peterson | 942e477 | 2008-11-08 17:07:06 +0000 | [diff] [blame] | 182 | The *flags* and *dont_inherit* arguments were added. |
Benjamin Peterson | 728c6f6 | 2008-11-08 17:04:18 +0000 | [diff] [blame] | 183 | |
| 184 | .. versionchanged:: 2.6 |
Georg Brandl | fc8eef3 | 2008-03-28 12:11:56 +0000 | [diff] [blame] | 185 | Support for compiling AST objects. |
| 186 | |
Benjamin Peterson | e36199b | 2009-11-12 23:39:44 +0000 | [diff] [blame] | 187 | .. versionchanged:: 2.7 |
| 188 | Allowed use of Windows and Mac newlines. Also input in ``'exec'`` mode |
| 189 | does not have to end in a newline anymore. |
| 190 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 191 | |
| 192 | .. function:: complex([real[, imag]]) |
| 193 | |
| 194 | Create a complex number with the value *real* + *imag*\*j or convert a string or |
| 195 | number to a complex number. If the first parameter is a string, it will be |
| 196 | interpreted as a complex number and the function must be called without a second |
| 197 | parameter. The second parameter can never be a string. Each argument may be any |
| 198 | numeric type (including complex). If *imag* is omitted, it defaults to zero and |
| 199 | the function serves as a numeric conversion function like :func:`int`, |
| 200 | :func:`long` and :func:`float`. If both arguments are omitted, returns ``0j``. |
| 201 | |
| 202 | The complex type is described in :ref:`typesnumeric`. |
| 203 | |
| 204 | |
| 205 | .. function:: delattr(object, name) |
| 206 | |
| 207 | This is a relative of :func:`setattr`. The arguments are an object and a |
| 208 | string. The string must be the name of one of the object's attributes. The |
| 209 | function deletes the named attribute, provided the object allows it. For |
| 210 | example, ``delattr(x, 'foobar')`` is equivalent to ``del x.foobar``. |
| 211 | |
| 212 | |
| 213 | .. function:: dict([arg]) |
| 214 | :noindex: |
| 215 | |
| 216 | Create a new data dictionary, optionally with items taken from *arg*. |
| 217 | The dictionary type is described in :ref:`typesmapping`. |
| 218 | |
| 219 | For other containers see the built in :class:`list`, :class:`set`, and |
| 220 | :class:`tuple` classes, and the :mod:`collections` module. |
| 221 | |
| 222 | |
| 223 | .. function:: dir([object]) |
| 224 | |
| 225 | Without arguments, return the list of names in the current local scope. With an |
| 226 | argument, attempt to return a list of valid attributes for that object. |
| 227 | |
| 228 | If the object has a method named :meth:`__dir__`, this method will be called and |
| 229 | must return the list of attributes. This allows objects that implement a custom |
| 230 | :func:`__getattr__` or :func:`__getattribute__` function to customize the way |
| 231 | :func:`dir` reports their attributes. |
| 232 | |
| 233 | If the object does not provide :meth:`__dir__`, the function tries its best to |
| 234 | gather information from the object's :attr:`__dict__` attribute, if defined, and |
| 235 | from its type object. The resulting list is not necessarily complete, and may |
| 236 | be inaccurate when the object has a custom :func:`__getattr__`. |
| 237 | |
| 238 | The default :func:`dir` mechanism behaves differently with different types of |
| 239 | objects, as it attempts to produce the most relevant, rather than complete, |
| 240 | information: |
| 241 | |
| 242 | * If the object is a module object, the list contains the names of the module's |
| 243 | attributes. |
| 244 | |
| 245 | * If the object is a type or class object, the list contains the names of its |
| 246 | attributes, and recursively of the attributes of its bases. |
| 247 | |
| 248 | * Otherwise, the list contains the object's attributes' names, the names of its |
| 249 | class's attributes, and recursively of the attributes of its class's base |
| 250 | classes. |
| 251 | |
Georg Brandl | 7a45ab8 | 2008-03-22 21:38:33 +0000 | [diff] [blame] | 252 | The resulting list is sorted alphabetically. For example: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 253 | |
| 254 | >>> import struct |
Georg Brandl | 7a45ab8 | 2008-03-22 21:38:33 +0000 | [diff] [blame] | 255 | >>> dir() # doctest: +SKIP |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 256 | ['__builtins__', '__doc__', '__name__', 'struct'] |
Georg Brandl | 7a45ab8 | 2008-03-22 21:38:33 +0000 | [diff] [blame] | 257 | >>> dir(struct) # doctest: +NORMALIZE_WHITESPACE |
| 258 | ['Struct', '__builtins__', '__doc__', '__file__', '__name__', |
| 259 | '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', |
| 260 | 'unpack', 'unpack_from'] |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 261 | >>> class Foo(object): |
| 262 | ... def __dir__(self): |
| 263 | ... return ["kan", "ga", "roo"] |
| 264 | ... |
| 265 | >>> f = Foo() |
| 266 | >>> dir(f) |
| 267 | ['ga', 'kan', 'roo'] |
| 268 | |
| 269 | .. note:: |
| 270 | |
| 271 | Because :func:`dir` is supplied primarily as a convenience for use at an |
| 272 | interactive prompt, it tries to supply an interesting set of names more than it |
| 273 | tries to supply a rigorously or consistently defined set of names, and its |
Georg Brandl | 91a4808 | 2008-01-06 15:48:20 +0000 | [diff] [blame] | 274 | detailed behavior may change across releases. For example, metaclass attributes |
| 275 | are not in the result list when the argument is a class. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 276 | |
| 277 | |
| 278 | .. function:: divmod(a, b) |
| 279 | |
| 280 | Take two (non complex) numbers as arguments and return a pair of numbers |
| 281 | consisting of their quotient and remainder when using long division. With mixed |
| 282 | operand types, the rules for binary arithmetic operators apply. For plain and |
| 283 | long integers, the result is the same as ``(a // b, a % b)``. For floating point |
| 284 | numbers the result is ``(q, a % b)``, where *q* is usually ``math.floor(a / b)`` |
| 285 | but may be 1 less than that. In any case ``q * b + a % b`` is very close to |
| 286 | *a*, if ``a % b`` is non-zero it has the same sign as *b*, and ``0 <= abs(a % b) |
| 287 | < abs(b)``. |
| 288 | |
| 289 | .. versionchanged:: 2.3 |
| 290 | Using :func:`divmod` with complex numbers is deprecated. |
| 291 | |
| 292 | |
Georg Brandl | 9138357 | 2008-05-13 19:04:54 +0000 | [diff] [blame] | 293 | .. function:: enumerate(sequence[, start=0]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 294 | |
Georg Brandl | 21f990c | 2008-05-12 16:53:42 +0000 | [diff] [blame] | 295 | Return an enumerate object. *sequence* must be a sequence, an |
| 296 | :term:`iterator`, or some other object which supports iteration. The |
Georg Brandl | 9fa61bb | 2009-07-26 14:19:57 +0000 | [diff] [blame] | 297 | :meth:`!next` method of the iterator returned by :func:`enumerate` returns a |
Georg Brandl | 9138357 | 2008-05-13 19:04:54 +0000 | [diff] [blame] | 298 | tuple containing a count (from *start* which defaults to 0) and the |
| 299 | corresponding value obtained from iterating over *iterable*. |
| 300 | :func:`enumerate` is useful for obtaining an indexed series: ``(0, seq[0])``, |
| 301 | ``(1, seq[1])``, ``(2, seq[2])``, .... For example: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 302 | |
Georg Brandl | 7a45ab8 | 2008-03-22 21:38:33 +0000 | [diff] [blame] | 303 | >>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']): |
| 304 | ... print i, season |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 305 | 0 Spring |
| 306 | 1 Summer |
| 307 | 2 Fall |
| 308 | 3 Winter |
| 309 | |
| 310 | .. versionadded:: 2.3 |
Georg Brandl | 9138357 | 2008-05-13 19:04:54 +0000 | [diff] [blame] | 311 | .. versionadded:: 2.6 |
| 312 | The *start* parameter. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 313 | |
| 314 | |
| 315 | .. function:: eval(expression[, globals[, locals]]) |
| 316 | |
| 317 | The arguments are a string and optional globals and locals. If provided, |
| 318 | *globals* must be a dictionary. If provided, *locals* can be any mapping |
| 319 | object. |
| 320 | |
| 321 | .. versionchanged:: 2.4 |
| 322 | formerly *locals* was required to be a dictionary. |
| 323 | |
| 324 | The *expression* argument is parsed and evaluated as a Python expression |
| 325 | (technically speaking, a condition list) using the *globals* and *locals* |
Georg Brandl | a739503 | 2007-10-21 12:15:05 +0000 | [diff] [blame] | 326 | dictionaries as global and local namespace. If the *globals* dictionary is |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 327 | present and lacks '__builtins__', the current globals are copied into *globals* |
| 328 | before *expression* is parsed. This means that *expression* normally has full |
| 329 | access to the standard :mod:`__builtin__` module and restricted environments are |
| 330 | propagated. If the *locals* dictionary is omitted it defaults to the *globals* |
| 331 | dictionary. If both dictionaries are omitted, the expression is executed in the |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 332 | environment where :func:`eval` is called. The return value is the result of |
Georg Brandl | 7a45ab8 | 2008-03-22 21:38:33 +0000 | [diff] [blame] | 333 | the evaluated expression. Syntax errors are reported as exceptions. Example: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 334 | |
| 335 | >>> x = 1 |
| 336 | >>> print eval('x+1') |
| 337 | 2 |
| 338 | |
Georg Brandl | 6140651 | 2008-08-30 10:03:09 +0000 | [diff] [blame] | 339 | This function can also be used to execute arbitrary code objects (such as |
| 340 | those created by :func:`compile`). In this case pass a code object instead |
| 341 | of a string. If the code object has been compiled with ``'exec'`` as the |
Georg Brandl | 118c557 | 2010-03-21 09:01:27 +0000 | [diff] [blame] | 342 | *mode* argument, :func:`eval`\'s return value will be ``None``. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 343 | |
| 344 | Hints: dynamic execution of statements is supported by the :keyword:`exec` |
| 345 | statement. Execution of statements from a file is supported by the |
| 346 | :func:`execfile` function. The :func:`globals` and :func:`locals` functions |
| 347 | returns the current global and local dictionary, respectively, which may be |
| 348 | useful to pass around for use by :func:`eval` or :func:`execfile`. |
| 349 | |
| 350 | |
| 351 | .. function:: execfile(filename[, globals[, locals]]) |
| 352 | |
| 353 | This function is similar to the :keyword:`exec` statement, but parses a file |
| 354 | instead of a string. It is different from the :keyword:`import` statement in |
| 355 | that it does not use the module administration --- it reads the file |
| 356 | unconditionally and does not create a new module. [#]_ |
| 357 | |
| 358 | The arguments are a file name and two optional dictionaries. The file is parsed |
| 359 | and evaluated as a sequence of Python statements (similarly to a module) using |
| 360 | the *globals* and *locals* dictionaries as global and local namespace. If |
| 361 | provided, *locals* can be any mapping object. |
| 362 | |
| 363 | .. versionchanged:: 2.4 |
| 364 | formerly *locals* was required to be a dictionary. |
| 365 | |
| 366 | If the *locals* dictionary is omitted it defaults to the *globals* dictionary. |
| 367 | If both dictionaries are omitted, the expression is executed in the environment |
| 368 | where :func:`execfile` is called. The return value is ``None``. |
| 369 | |
Georg Brandl | 16a57f6 | 2009-04-27 15:29:09 +0000 | [diff] [blame] | 370 | .. note:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 371 | |
| 372 | The default *locals* act as described for function :func:`locals` below: |
| 373 | modifications to the default *locals* dictionary should not be attempted. Pass |
| 374 | an explicit *locals* dictionary if you need to see effects of the code on |
| 375 | *locals* after function :func:`execfile` returns. :func:`execfile` cannot be |
| 376 | used reliably to modify a function's locals. |
| 377 | |
| 378 | |
| 379 | .. function:: file(filename[, mode[, bufsize]]) |
| 380 | |
| 381 | Constructor function for the :class:`file` type, described further in section |
| 382 | :ref:`bltin-file-objects`. The constructor's arguments are the same as those |
| 383 | of the :func:`open` built-in function described below. |
| 384 | |
| 385 | When opening a file, it's preferable to use :func:`open` instead of invoking |
| 386 | this constructor directly. :class:`file` is more suited to type testing (for |
| 387 | example, writing ``isinstance(f, file)``). |
| 388 | |
| 389 | .. versionadded:: 2.2 |
| 390 | |
| 391 | |
| 392 | .. function:: filter(function, iterable) |
| 393 | |
| 394 | Construct a list from those elements of *iterable* for which *function* returns |
| 395 | true. *iterable* may be either a sequence, a container which supports |
Georg Brandl | e7a0990 | 2007-10-21 12:10:28 +0000 | [diff] [blame] | 396 | iteration, or an iterator. If *iterable* is a string or a tuple, the result |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 397 | also has that type; otherwise it is always a list. If *function* is ``None``, |
| 398 | the identity function is assumed, that is, all elements of *iterable* that are |
| 399 | false are removed. |
| 400 | |
| 401 | Note that ``filter(function, iterable)`` is equivalent to ``[item for item in |
| 402 | iterable if function(item)]`` if function is not ``None`` and ``[item for item |
| 403 | in iterable if item]`` if function is ``None``. |
| 404 | |
Georg Brandl | 5ac9d87 | 2010-07-04 17:28:33 +0000 | [diff] [blame] | 405 | See :func:`itertools.ifilter` and :func:`itertools.ifilterfalse` for iterator |
| 406 | versions of this function, including a variation that filters for elements |
| 407 | where the *function* returns false. |
Raymond Hettinger | f9bce83 | 2009-02-19 05:34:35 +0000 | [diff] [blame] | 408 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 409 | |
| 410 | .. function:: float([x]) |
| 411 | |
| 412 | Convert a string or a number to floating point. If the argument is a string, it |
| 413 | must contain a possibly signed decimal or floating point number, possibly |
Christian Heimes | 0a8143f | 2007-12-18 23:22:54 +0000 | [diff] [blame] | 414 | embedded in whitespace. The argument may also be [+|-]nan or [+|-]inf. |
| 415 | Otherwise, the argument may be a plain or long integer |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 416 | or a floating point number, and a floating point number with the same value |
| 417 | (within Python's floating point precision) is returned. If no argument is |
| 418 | given, returns ``0.0``. |
| 419 | |
| 420 | .. note:: |
| 421 | |
| 422 | .. index:: |
| 423 | single: NaN |
| 424 | single: Infinity |
| 425 | |
| 426 | When passing in a string, values for NaN and Infinity may be returned, depending |
Christian Heimes | 0a8143f | 2007-12-18 23:22:54 +0000 | [diff] [blame] | 427 | on the underlying C library. Float accepts the strings nan, inf and -inf for |
| 428 | NaN and positive or negative infinity. The case and a leading + are ignored as |
| 429 | well as a leading - is ignored for NaN. Float always represents NaN and infinity |
| 430 | as nan, inf or -inf. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 431 | |
| 432 | The float type is described in :ref:`typesnumeric`. |
| 433 | |
Georg Brandl | 528f881 | 2009-02-23 10:24:23 +0000 | [diff] [blame] | 434 | |
| 435 | .. function:: format(value[, format_spec]) |
| 436 | |
| 437 | .. index:: |
| 438 | pair: str; format |
| 439 | single: __format__ |
| 440 | |
| 441 | Convert a *value* to a "formatted" representation, as controlled by |
| 442 | *format_spec*. The interpretation of *format_spec* will depend on the type |
| 443 | of the *value* argument, however there is a standard formatting syntax that |
| 444 | is used by most built-in types: :ref:`formatspec`. |
| 445 | |
| 446 | .. note:: |
| 447 | |
| 448 | ``format(value, format_spec)`` merely calls |
| 449 | ``value.__format__(format_spec)``. |
| 450 | |
| 451 | .. versionadded:: 2.6 |
| 452 | |
| 453 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 454 | .. function:: frozenset([iterable]) |
| 455 | :noindex: |
| 456 | |
| 457 | Return a frozenset object, optionally with elements taken from *iterable*. |
| 458 | The frozenset type is described in :ref:`types-set`. |
| 459 | |
| 460 | For other containers see the built in :class:`dict`, :class:`list`, and |
| 461 | :class:`tuple` classes, and the :mod:`collections` module. |
| 462 | |
| 463 | .. versionadded:: 2.4 |
| 464 | |
| 465 | |
| 466 | .. function:: getattr(object, name[, default]) |
| 467 | |
| 468 | Return the value of the named attributed of *object*. *name* must be a string. |
| 469 | If the string is the name of one of the object's attributes, the result is the |
| 470 | value of that attribute. For example, ``getattr(x, 'foobar')`` is equivalent to |
| 471 | ``x.foobar``. If the named attribute does not exist, *default* is returned if |
| 472 | provided, otherwise :exc:`AttributeError` is raised. |
| 473 | |
| 474 | |
| 475 | .. function:: globals() |
| 476 | |
| 477 | Return a dictionary representing the current global symbol table. This is always |
| 478 | the dictionary of the current module (inside a function or method, this is the |
| 479 | module where it is defined, not the module from which it is called). |
| 480 | |
| 481 | |
| 482 | .. function:: hasattr(object, name) |
| 483 | |
| 484 | The arguments are an object and a string. The result is ``True`` if the string |
| 485 | is the name of one of the object's attributes, ``False`` if not. (This is |
| 486 | implemented by calling ``getattr(object, name)`` and seeing whether it raises an |
| 487 | exception or not.) |
| 488 | |
| 489 | |
| 490 | .. function:: hash(object) |
| 491 | |
| 492 | Return the hash value of the object (if it has one). Hash values are integers. |
| 493 | They are used to quickly compare dictionary keys during a dictionary lookup. |
| 494 | Numeric values that compare equal have the same hash value (even if they are of |
| 495 | different types, as is the case for 1 and 1.0). |
| 496 | |
| 497 | |
| 498 | .. function:: help([object]) |
| 499 | |
| 500 | Invoke the built-in help system. (This function is intended for interactive |
| 501 | use.) If no argument is given, the interactive help system starts on the |
| 502 | interpreter console. If the argument is a string, then the string is looked up |
| 503 | as the name of a module, function, class, method, keyword, or documentation |
| 504 | topic, and a help page is printed on the console. If the argument is any other |
| 505 | kind of object, a help page on the object is generated. |
| 506 | |
Georg Brandl | 92058d2 | 2008-01-20 13:08:37 +0000 | [diff] [blame] | 507 | This function is added to the built-in namespace by the :mod:`site` module. |
| 508 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 509 | .. versionadded:: 2.2 |
| 510 | |
| 511 | |
| 512 | .. function:: hex(x) |
| 513 | |
| 514 | Convert an integer number (of any size) to a hexadecimal string. The result is a |
| 515 | valid Python expression. |
| 516 | |
Mark Dickinson | 530df33 | 2009-10-03 10:14:34 +0000 | [diff] [blame] | 517 | .. note:: |
| 518 | |
| 519 | To obtain a hexadecimal string representation for a float, use the |
| 520 | :meth:`float.hex` method. |
| 521 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 522 | .. versionchanged:: 2.4 |
| 523 | Formerly only returned an unsigned literal. |
| 524 | |
| 525 | |
| 526 | .. function:: id(object) |
| 527 | |
| 528 | Return the "identity" of an object. This is an integer (or long integer) which |
| 529 | is guaranteed to be unique and constant for this object during its lifetime. |
Georg Brandl | 6c14e58 | 2009-10-22 11:48:10 +0000 | [diff] [blame] | 530 | Two objects with non-overlapping lifetimes may have the same :func:`id` |
| 531 | value. |
| 532 | |
| 533 | .. impl-detail:: This is the address of the object. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 534 | |
| 535 | |
| 536 | .. function:: input([prompt]) |
| 537 | |
| 538 | Equivalent to ``eval(raw_input(prompt))``. |
| 539 | |
| 540 | .. warning:: |
| 541 | |
| 542 | This function is not safe from user errors! It expects a valid Python |
| 543 | expression as input; if the input is not syntactically valid, a |
| 544 | :exc:`SyntaxError` will be raised. Other exceptions may be raised if there is an |
| 545 | error during evaluation. (On the other hand, sometimes this is exactly what you |
| 546 | need when writing a quick script for expert use.) |
| 547 | |
| 548 | If the :mod:`readline` module was loaded, then :func:`input` will use it to |
| 549 | provide elaborate line editing and history features. |
| 550 | |
| 551 | Consider using the :func:`raw_input` function for general input from users. |
| 552 | |
| 553 | |
Georg Brandl | 29bc2cd | 2009-08-06 15:06:25 +0000 | [diff] [blame] | 554 | .. function:: int([x[, base]]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 555 | |
Georg Brandl | e418625 | 2007-09-24 17:59:28 +0000 | [diff] [blame] | 556 | Convert a string or number to a plain integer. If the argument is a string, |
| 557 | it must contain a possibly signed decimal number representable as a Python |
Georg Brandl | 29bc2cd | 2009-08-06 15:06:25 +0000 | [diff] [blame] | 558 | integer, possibly embedded in whitespace. The *base* parameter gives the |
Georg Brandl | e418625 | 2007-09-24 17:59:28 +0000 | [diff] [blame] | 559 | base for the conversion (which is 10 by default) and may be any integer in |
Georg Brandl | 29bc2cd | 2009-08-06 15:06:25 +0000 | [diff] [blame] | 560 | the range [2, 36], or zero. If *base* is zero, the proper radix is |
Benjamin Peterson | 881c487 | 2008-09-14 16:02:22 +0000 | [diff] [blame] | 561 | determined based on the contents of string; the interpretation is the same as |
Georg Brandl | 29bc2cd | 2009-08-06 15:06:25 +0000 | [diff] [blame] | 562 | for integer literals. (See :ref:`numbers`.) If *base* is specified and *x* |
Benjamin Peterson | 881c487 | 2008-09-14 16:02:22 +0000 | [diff] [blame] | 563 | is not a string, :exc:`TypeError` is raised. Otherwise, the argument may be a |
| 564 | plain or long integer or a floating point number. Conversion of floating |
| 565 | point numbers to integers truncates (towards zero). If the argument is |
| 566 | outside the integer range a long object will be returned instead. If no |
| 567 | arguments are given, returns ``0``. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 568 | |
| 569 | The integer type is described in :ref:`typesnumeric`. |
| 570 | |
| 571 | |
| 572 | .. function:: isinstance(object, classinfo) |
| 573 | |
| 574 | Return true if the *object* argument is an instance of the *classinfo* argument, |
| 575 | or of a (direct or indirect) subclass thereof. Also return true if *classinfo* |
| 576 | is a type object (new-style class) and *object* is an object of that type or of |
| 577 | a (direct or indirect) subclass thereof. If *object* is not a class instance or |
| 578 | an object of the given type, the function always returns false. If *classinfo* |
| 579 | is neither a class object nor a type object, it may be a tuple of class or type |
| 580 | objects, or may recursively contain other such tuples (other sequence types are |
| 581 | not accepted). If *classinfo* is not a class, type, or tuple of classes, types, |
| 582 | and such tuples, a :exc:`TypeError` exception is raised. |
| 583 | |
| 584 | .. versionchanged:: 2.2 |
| 585 | Support for a tuple of type information was added. |
| 586 | |
| 587 | |
| 588 | .. function:: issubclass(class, classinfo) |
| 589 | |
| 590 | Return true if *class* is a subclass (direct or indirect) of *classinfo*. A |
| 591 | class is considered a subclass of itself. *classinfo* may be a tuple of class |
| 592 | objects, in which case every entry in *classinfo* will be checked. In any other |
| 593 | case, a :exc:`TypeError` exception is raised. |
| 594 | |
| 595 | .. versionchanged:: 2.3 |
| 596 | Support for a tuple of type information was added. |
| 597 | |
| 598 | |
| 599 | .. function:: iter(o[, sentinel]) |
| 600 | |
Georg Brandl | e7a0990 | 2007-10-21 12:10:28 +0000 | [diff] [blame] | 601 | Return an :term:`iterator` object. The first argument is interpreted very differently |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 602 | depending on the presence of the second argument. Without a second argument, *o* |
| 603 | must be a collection object which supports the iteration protocol (the |
| 604 | :meth:`__iter__` method), or it must support the sequence protocol (the |
| 605 | :meth:`__getitem__` method with integer arguments starting at ``0``). If it |
| 606 | does not support either of those protocols, :exc:`TypeError` is raised. If the |
| 607 | second argument, *sentinel*, is given, then *o* must be a callable object. The |
| 608 | iterator created in this case will call *o* with no arguments for each call to |
Georg Brandl | 9fa61bb | 2009-07-26 14:19:57 +0000 | [diff] [blame] | 609 | its :meth:`~iterator.next` method; if the value returned is equal to *sentinel*, |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 610 | :exc:`StopIteration` will be raised, otherwise the value will be returned. |
| 611 | |
Benjamin Peterson | 06919a1 | 2009-03-18 20:58:09 +0000 | [diff] [blame] | 612 | One useful application of the second form of :func:`iter` is to read lines of |
| 613 | a file until a certain line is reached. The following example reads a file |
| 614 | until ``"STOP"`` is reached: :: |
Benjamin Peterson | ed3558b | 2009-03-17 20:29:51 +0000 | [diff] [blame] | 615 | |
Benjamin Peterson | 06919a1 | 2009-03-18 20:58:09 +0000 | [diff] [blame] | 616 | with open("mydata.txt") as fp: |
| 617 | for line in iter(fp.readline, "STOP"): |
| 618 | process_line(line) |
Benjamin Peterson | ed3558b | 2009-03-17 20:29:51 +0000 | [diff] [blame] | 619 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 620 | .. versionadded:: 2.2 |
| 621 | |
| 622 | |
| 623 | .. function:: len(s) |
| 624 | |
| 625 | Return the length (the number of items) of an object. The argument may be a |
| 626 | sequence (string, tuple or list) or a mapping (dictionary). |
| 627 | |
| 628 | |
| 629 | .. function:: list([iterable]) |
| 630 | |
| 631 | Return a list whose items are the same and in the same order as *iterable*'s |
| 632 | items. *iterable* may be either a sequence, a container that supports |
| 633 | iteration, or an iterator object. If *iterable* is already a list, a copy is |
| 634 | made and returned, similar to ``iterable[:]``. For instance, ``list('abc')`` |
| 635 | returns ``['a', 'b', 'c']`` and ``list( (1, 2, 3) )`` returns ``[1, 2, 3]``. If |
| 636 | no argument is given, returns a new empty list, ``[]``. |
| 637 | |
| 638 | :class:`list` is a mutable sequence type, as documented in |
| 639 | :ref:`typesseq`. For other containers see the built in :class:`dict`, |
| 640 | :class:`set`, and :class:`tuple` classes, and the :mod:`collections` module. |
| 641 | |
| 642 | |
| 643 | .. function:: locals() |
| 644 | |
| 645 | Update and return a dictionary representing the current local symbol table. |
Georg Brandl | 54967d9 | 2009-09-18 21:21:41 +0000 | [diff] [blame] | 646 | Free variables are returned by :func:`locals` when it is called in function |
| 647 | blocks, but not in class blocks. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 648 | |
Georg Brandl | 16a57f6 | 2009-04-27 15:29:09 +0000 | [diff] [blame] | 649 | .. note:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 650 | |
Georg Brandl | 54967d9 | 2009-09-18 21:21:41 +0000 | [diff] [blame] | 651 | The contents of this dictionary should not be modified; changes may not |
| 652 | affect the values of local and free variables used by the interpreter. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 653 | |
| 654 | |
Georg Brandl | 29bc2cd | 2009-08-06 15:06:25 +0000 | [diff] [blame] | 655 | .. function:: long([x[, base]]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 656 | |
| 657 | Convert a string or number to a long integer. If the argument is a string, it |
| 658 | must contain a possibly signed number of arbitrary size, possibly embedded in |
Georg Brandl | 29bc2cd | 2009-08-06 15:06:25 +0000 | [diff] [blame] | 659 | whitespace. The *base* argument is interpreted in the same way as for |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 660 | :func:`int`, and may only be given when *x* is a string. Otherwise, the argument |
| 661 | may be a plain or long integer or a floating point number, and a long integer |
| 662 | with the same value is returned. Conversion of floating point numbers to |
| 663 | integers truncates (towards zero). If no arguments are given, returns ``0L``. |
| 664 | |
| 665 | The long type is described in :ref:`typesnumeric`. |
| 666 | |
Georg Brandl | 29bc2cd | 2009-08-06 15:06:25 +0000 | [diff] [blame] | 667 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 668 | .. function:: map(function, iterable, ...) |
| 669 | |
| 670 | Apply *function* to every item of *iterable* and return a list of the results. |
| 671 | If additional *iterable* arguments are passed, *function* must take that many |
| 672 | arguments and is applied to the items from all iterables in parallel. If one |
| 673 | iterable is shorter than another it is assumed to be extended with ``None`` |
| 674 | items. If *function* is ``None``, the identity function is assumed; if there |
| 675 | are multiple arguments, :func:`map` returns a list consisting of tuples |
| 676 | containing the corresponding items from all iterables (a kind of transpose |
| 677 | operation). The *iterable* arguments may be a sequence or any iterable object; |
| 678 | the result is always a list. |
| 679 | |
| 680 | |
| 681 | .. function:: max(iterable[, args...][key]) |
| 682 | |
| 683 | With a single argument *iterable*, return the largest item of a non-empty |
| 684 | iterable (such as a string, tuple or list). With more than one argument, return |
| 685 | the largest of the arguments. |
| 686 | |
| 687 | The optional *key* argument specifies a one-argument ordering function like that |
| 688 | used for :meth:`list.sort`. The *key* argument, if supplied, must be in keyword |
| 689 | form (for example, ``max(a,b,c,key=func)``). |
| 690 | |
| 691 | .. versionchanged:: 2.5 |
| 692 | Added support for the optional *key* argument. |
| 693 | |
| 694 | |
Antoine Pitrou | 789be0c | 2009-04-02 21:18:34 +0000 | [diff] [blame] | 695 | .. function:: memoryview(obj) |
| 696 | :noindex: |
| 697 | |
| 698 | Return a "memory view" object created from the given argument. See |
| 699 | :ref:`typememoryview` for more information. |
| 700 | |
| 701 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 702 | .. function:: min(iterable[, args...][key]) |
| 703 | |
| 704 | With a single argument *iterable*, return the smallest item of a non-empty |
| 705 | iterable (such as a string, tuple or list). With more than one argument, return |
| 706 | the smallest of the arguments. |
| 707 | |
| 708 | The optional *key* argument specifies a one-argument ordering function like that |
| 709 | used for :meth:`list.sort`. The *key* argument, if supplied, must be in keyword |
| 710 | form (for example, ``min(a,b,c,key=func)``). |
| 711 | |
| 712 | .. versionchanged:: 2.5 |
| 713 | Added support for the optional *key* argument. |
| 714 | |
| 715 | |
Georg Brandl | 28e0873 | 2008-04-30 19:47:09 +0000 | [diff] [blame] | 716 | .. function:: next(iterator[, default]) |
| 717 | |
Georg Brandl | 9fa61bb | 2009-07-26 14:19:57 +0000 | [diff] [blame] | 718 | Retrieve the next item from the *iterator* by calling its |
| 719 | :meth:`~iterator.next` method. If *default* is given, it is returned if the |
| 720 | iterator is exhausted, otherwise :exc:`StopIteration` is raised. |
Georg Brandl | 28e0873 | 2008-04-30 19:47:09 +0000 | [diff] [blame] | 721 | |
| 722 | .. versionadded:: 2.6 |
| 723 | |
| 724 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 725 | .. function:: object() |
| 726 | |
| 727 | Return a new featureless object. :class:`object` is a base for all new style |
| 728 | classes. It has the methods that are common to all instances of new style |
| 729 | classes. |
| 730 | |
| 731 | .. versionadded:: 2.2 |
| 732 | |
| 733 | .. versionchanged:: 2.3 |
| 734 | This function does not accept any arguments. Formerly, it accepted arguments but |
| 735 | ignored them. |
| 736 | |
| 737 | |
| 738 | .. function:: oct(x) |
| 739 | |
| 740 | Convert an integer number (of any size) to an octal string. The result is a |
| 741 | valid Python expression. |
| 742 | |
| 743 | .. versionchanged:: 2.4 |
| 744 | Formerly only returned an unsigned literal. |
| 745 | |
| 746 | |
| 747 | .. function:: open(filename[, mode[, bufsize]]) |
| 748 | |
| 749 | Open a file, returning an object of the :class:`file` type described in |
| 750 | section :ref:`bltin-file-objects`. If the file cannot be opened, |
| 751 | :exc:`IOError` is raised. When opening a file, it's preferable to use |
| 752 | :func:`open` instead of invoking the :class:`file` constructor directly. |
| 753 | |
| 754 | The first two arguments are the same as for ``stdio``'s :cfunc:`fopen`: |
| 755 | *filename* is the file name to be opened, and *mode* is a string indicating how |
| 756 | the file is to be opened. |
| 757 | |
| 758 | The most commonly-used values of *mode* are ``'r'`` for reading, ``'w'`` for |
| 759 | writing (truncating the file if it already exists), and ``'a'`` for appending |
| 760 | (which on *some* Unix systems means that *all* writes append to the end of the |
| 761 | file regardless of the current seek position). If *mode* is omitted, it |
Georg Brandl | 9f1e2ec | 2008-01-13 09:36:18 +0000 | [diff] [blame] | 762 | defaults to ``'r'``. The default is to use text mode, which may convert |
| 763 | ``'\n'`` characters to a platform-specific representation on writing and back |
| 764 | on reading. Thus, when opening a binary file, you should append ``'b'`` to |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 765 | the *mode* value to open the file in binary mode, which will improve |
| 766 | portability. (Appending ``'b'`` is useful even on systems that don't treat |
| 767 | binary and text files differently, where it serves as documentation.) See below |
| 768 | for more possible values of *mode*. |
| 769 | |
| 770 | .. index:: |
| 771 | single: line-buffered I/O |
| 772 | single: unbuffered I/O |
| 773 | single: buffer size, I/O |
| 774 | single: I/O control; buffering |
| 775 | |
| 776 | The optional *bufsize* argument specifies the file's desired buffer size: 0 |
| 777 | means unbuffered, 1 means line buffered, any other positive value means use a |
| 778 | buffer of (approximately) that size. A negative *bufsize* means to use the |
| 779 | system default, which is usually line buffered for tty devices and fully |
| 780 | buffered for other files. If omitted, the system default is used. [#]_ |
| 781 | |
| 782 | Modes ``'r+'``, ``'w+'`` and ``'a+'`` open the file for updating (note that |
| 783 | ``'w+'`` truncates the file). Append ``'b'`` to the mode to open the file in |
| 784 | binary mode, on systems that differentiate between binary and text files; on |
| 785 | systems that don't have this distinction, adding the ``'b'`` has no effect. |
| 786 | |
| 787 | In addition to the standard :cfunc:`fopen` values *mode* may be ``'U'`` or |
| 788 | ``'rU'``. Python is usually built with universal newline support; supplying |
| 789 | ``'U'`` opens the file as a text file, but lines may be terminated by any of the |
| 790 | following: the Unix end-of-line convention ``'\n'``, the Macintosh convention |
| 791 | ``'\r'``, or the Windows convention ``'\r\n'``. All of these external |
| 792 | representations are seen as ``'\n'`` by the Python program. If Python is built |
| 793 | without universal newline support a *mode* with ``'U'`` is the same as normal |
| 794 | text mode. Note that file objects so opened also have an attribute called |
| 795 | :attr:`newlines` which has a value of ``None`` (if no newlines have yet been |
| 796 | seen), ``'\n'``, ``'\r'``, ``'\r\n'``, or a tuple containing all the newline |
| 797 | types seen. |
| 798 | |
| 799 | Python enforces that the mode, after stripping ``'U'``, begins with ``'r'``, |
| 800 | ``'w'`` or ``'a'``. |
| 801 | |
Mark Summerfield | ac3d429 | 2007-11-02 08:24:59 +0000 | [diff] [blame] | 802 | Python provides many file handling modules including |
| 803 | :mod:`fileinput`, :mod:`os`, :mod:`os.path`, :mod:`tempfile`, and |
| 804 | :mod:`shutil`. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 805 | |
| 806 | .. versionchanged:: 2.5 |
| 807 | Restriction on first letter of mode string introduced. |
| 808 | |
| 809 | |
| 810 | .. function:: ord(c) |
| 811 | |
| 812 | Given a string of length one, return an integer representing the Unicode code |
| 813 | point of the character when the argument is a unicode object, or the value of |
| 814 | the byte when the argument is an 8-bit string. For example, ``ord('a')`` returns |
| 815 | the integer ``97``, ``ord(u'\u2020')`` returns ``8224``. This is the inverse of |
| 816 | :func:`chr` for 8-bit strings and of :func:`unichr` for unicode objects. If a |
| 817 | unicode argument is given and Python was built with UCS2 Unicode, then the |
| 818 | character's code point must be in the range [0..65535] inclusive; otherwise the |
| 819 | string length is two, and a :exc:`TypeError` will be raised. |
| 820 | |
| 821 | |
| 822 | .. function:: pow(x, y[, z]) |
| 823 | |
| 824 | Return *x* to the power *y*; if *z* is present, return *x* to the power *y*, |
| 825 | modulo *z* (computed more efficiently than ``pow(x, y) % z``). The two-argument |
| 826 | form ``pow(x, y)`` is equivalent to using the power operator: ``x**y``. |
| 827 | |
| 828 | The arguments must have numeric types. With mixed operand types, the coercion |
| 829 | rules for binary arithmetic operators apply. For int and long int operands, the |
| 830 | result has the same type as the operands (after coercion) unless the second |
| 831 | argument is negative; in that case, all arguments are converted to float and a |
| 832 | float result is delivered. For example, ``10**2`` returns ``100``, but |
| 833 | ``10**-2`` returns ``0.01``. (This last feature was added in Python 2.2. In |
| 834 | Python 2.1 and before, if both arguments were of integer types and the second |
| 835 | argument was negative, an exception was raised.) If the second argument is |
| 836 | negative, the third argument must be omitted. If *z* is present, *x* and *y* |
| 837 | must be of integer types, and *y* must be non-negative. (This restriction was |
| 838 | added in Python 2.2. In Python 2.1 and before, floating 3-argument ``pow()`` |
| 839 | returned platform-dependent results depending on floating-point rounding |
| 840 | accidents.) |
| 841 | |
| 842 | |
Georg Brandl | e561011 | 2009-04-21 18:24:34 +0000 | [diff] [blame] | 843 | .. function:: print([object, ...][, sep=' '][, end='\\n'][, file=sys.stdout]) |
Georg Brandl | d346475 | 2008-03-21 19:37:57 +0000 | [diff] [blame] | 844 | |
| 845 | Print *object*\(s) to the stream *file*, separated by *sep* and followed by |
| 846 | *end*. *sep*, *end* and *file*, if present, must be given as keyword |
| 847 | arguments. |
| 848 | |
| 849 | All non-keyword arguments are converted to strings like :func:`str` does and |
| 850 | written to the stream, separated by *sep* and followed by *end*. Both *sep* |
| 851 | and *end* must be strings; they can also be ``None``, which means to use the |
| 852 | default values. If no *object* is given, :func:`print` will just write |
| 853 | *end*. |
| 854 | |
| 855 | The *file* argument must be an object with a ``write(string)`` method; if it |
| 856 | is not present or ``None``, :data:`sys.stdout` will be used. |
| 857 | |
| 858 | .. note:: |
| 859 | |
Georg Brandl | d7d4fd7 | 2009-07-26 14:37:28 +0000 | [diff] [blame] | 860 | This function is not normally available as a built-in since the name |
Georg Brandl | d346475 | 2008-03-21 19:37:57 +0000 | [diff] [blame] | 861 | ``print`` is recognized as the :keyword:`print` statement. To disable the |
| 862 | statement and use the :func:`print` function, use this future statement at |
| 863 | the top of your module:: |
| 864 | |
| 865 | from __future__ import print_function |
| 866 | |
| 867 | .. versionadded:: 2.6 |
| 868 | |
| 869 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 870 | .. function:: property([fget[, fset[, fdel[, doc]]]]) |
| 871 | |
Georg Brandl | a739503 | 2007-10-21 12:15:05 +0000 | [diff] [blame] | 872 | Return a property attribute for :term:`new-style class`\es (classes that |
| 873 | derive from :class:`object`). |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 874 | |
| 875 | *fget* is a function for getting an attribute value, likewise *fset* is a |
| 876 | function for setting, and *fdel* a function for del'ing, an attribute. Typical |
Georg Brandl | 7d4bfb3 | 2010-08-02 21:44:25 +0000 | [diff] [blame] | 877 | use is to define a managed attribute ``x``:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 878 | |
| 879 | class C(object): |
Georg Brandl | 2ac747c | 2008-05-11 08:47:53 +0000 | [diff] [blame] | 880 | def __init__(self): |
| 881 | self._x = None |
| 882 | |
| 883 | def getx(self): |
| 884 | return self._x |
| 885 | def setx(self, value): |
| 886 | self._x = value |
| 887 | def delx(self): |
| 888 | del self._x |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 889 | x = property(getx, setx, delx, "I'm the 'x' property.") |
| 890 | |
Georg Brandl | 7d4bfb3 | 2010-08-02 21:44:25 +0000 | [diff] [blame] | 891 | If then *c* is an instance of *C*, ``c.x`` will invoke the getter, |
| 892 | ``c.x = value`` will invoke the setter and ``del c.x`` the deleter. |
| 893 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 894 | If given, *doc* will be the docstring of the property attribute. Otherwise, the |
| 895 | property will copy *fget*'s docstring (if it exists). This makes it possible to |
Georg Brandl | 584265b | 2007-12-02 14:58:50 +0000 | [diff] [blame] | 896 | create read-only properties easily using :func:`property` as a :term:`decorator`:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 897 | |
| 898 | class Parrot(object): |
| 899 | def __init__(self): |
| 900 | self._voltage = 100000 |
| 901 | |
| 902 | @property |
| 903 | def voltage(self): |
| 904 | """Get the current voltage.""" |
| 905 | return self._voltage |
| 906 | |
Georg Brandl | 2ac747c | 2008-05-11 08:47:53 +0000 | [diff] [blame] | 907 | turns the :meth:`voltage` method into a "getter" for a read-only attribute |
| 908 | with the same name. |
| 909 | |
| 910 | A property object has :attr:`getter`, :attr:`setter`, and :attr:`deleter` |
| 911 | methods usable as decorators that create a copy of the property with the |
| 912 | corresponding accessor function set to the decorated function. This is |
| 913 | best explained with an example:: |
| 914 | |
| 915 | class C(object): |
Benjamin Peterson | 1fb8451 | 2008-10-15 21:58:46 +0000 | [diff] [blame] | 916 | def __init__(self): |
| 917 | self._x = None |
Georg Brandl | 2ac747c | 2008-05-11 08:47:53 +0000 | [diff] [blame] | 918 | |
| 919 | @property |
| 920 | def x(self): |
| 921 | """I'm the 'x' property.""" |
| 922 | return self._x |
| 923 | |
| 924 | @x.setter |
| 925 | def x(self, value): |
| 926 | self._x = value |
| 927 | |
| 928 | @x.deleter |
| 929 | def x(self): |
| 930 | del self._x |
| 931 | |
| 932 | This code is exactly equivalent to the first example. Be sure to give the |
| 933 | additional functions the same name as the original property (``x`` in this |
| 934 | case.) |
| 935 | |
| 936 | The returned property also has the attributes ``fget``, ``fset``, and |
| 937 | ``fdel`` corresponding to the constructor arguments. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 938 | |
| 939 | .. versionadded:: 2.2 |
| 940 | |
| 941 | .. versionchanged:: 2.5 |
| 942 | Use *fget*'s docstring if no *doc* given. |
| 943 | |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 944 | .. versionchanged:: 2.6 |
Georg Brandl | 2ac747c | 2008-05-11 08:47:53 +0000 | [diff] [blame] | 945 | The ``getter``, ``setter``, and ``deleter`` attributes were added. |
| 946 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 947 | |
| 948 | .. function:: range([start,] stop[, step]) |
| 949 | |
| 950 | This is a versatile function to create lists containing arithmetic progressions. |
| 951 | It is most often used in :keyword:`for` loops. The arguments must be plain |
| 952 | integers. If the *step* argument is omitted, it defaults to ``1``. If the |
| 953 | *start* argument is omitted, it defaults to ``0``. The full form returns a list |
| 954 | of plain integers ``[start, start + step, start + 2 * step, ...]``. If *step* |
| 955 | is positive, the last element is the largest ``start + i * step`` less than |
| 956 | *stop*; if *step* is negative, the last element is the smallest ``start + i * |
| 957 | step`` greater than *stop*. *step* must not be zero (or else :exc:`ValueError` |
Georg Brandl | 7a45ab8 | 2008-03-22 21:38:33 +0000 | [diff] [blame] | 958 | is raised). Example: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 959 | |
| 960 | >>> range(10) |
| 961 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
| 962 | >>> range(1, 11) |
| 963 | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
| 964 | >>> range(0, 30, 5) |
| 965 | [0, 5, 10, 15, 20, 25] |
| 966 | >>> range(0, 10, 3) |
| 967 | [0, 3, 6, 9] |
| 968 | >>> range(0, -10, -1) |
| 969 | [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] |
| 970 | >>> range(0) |
| 971 | [] |
| 972 | >>> range(1, 0) |
| 973 | [] |
| 974 | |
| 975 | |
| 976 | .. function:: raw_input([prompt]) |
| 977 | |
| 978 | If the *prompt* argument is present, it is written to standard output without a |
| 979 | trailing newline. The function then reads a line from input, converts it to a |
| 980 | string (stripping a trailing newline), and returns that. When EOF is read, |
| 981 | :exc:`EOFError` is raised. Example:: |
| 982 | |
| 983 | >>> s = raw_input('--> ') |
| 984 | --> Monty Python's Flying Circus |
| 985 | >>> s |
| 986 | "Monty Python's Flying Circus" |
| 987 | |
| 988 | If the :mod:`readline` module was loaded, then :func:`raw_input` will use it to |
| 989 | provide elaborate line editing and history features. |
| 990 | |
| 991 | |
| 992 | .. function:: reduce(function, iterable[, initializer]) |
| 993 | |
| 994 | Apply *function* of two arguments cumulatively to the items of *iterable*, from |
| 995 | left to right, so as to reduce the iterable to a single value. For example, |
| 996 | ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``. |
| 997 | The left argument, *x*, is the accumulated value and the right argument, *y*, is |
| 998 | the update value from the *iterable*. If the optional *initializer* is present, |
| 999 | it is placed before the items of the iterable in the calculation, and serves as |
| 1000 | a default when the iterable is empty. If *initializer* is not given and |
| 1001 | *iterable* contains only one item, the first item is returned. |
| 1002 | |
| 1003 | |
| 1004 | .. function:: reload(module) |
| 1005 | |
| 1006 | Reload a previously imported *module*. The argument must be a module object, so |
| 1007 | it must have been successfully imported before. This is useful if you have |
| 1008 | edited the module source file using an external editor and want to try out the |
| 1009 | new version without leaving the Python interpreter. The return value is the |
| 1010 | module object (the same as the *module* argument). |
| 1011 | |
| 1012 | When ``reload(module)`` is executed: |
| 1013 | |
| 1014 | * Python modules' code is recompiled and the module-level code reexecuted, |
| 1015 | defining a new set of objects which are bound to names in the module's |
| 1016 | dictionary. The ``init`` function of extension modules is not called a second |
| 1017 | time. |
| 1018 | |
| 1019 | * As with all other objects in Python the old objects are only reclaimed after |
| 1020 | their reference counts drop to zero. |
| 1021 | |
| 1022 | * The names in the module namespace are updated to point to any new or changed |
| 1023 | objects. |
| 1024 | |
| 1025 | * Other references to the old objects (such as names external to the module) are |
| 1026 | not rebound to refer to the new objects and must be updated in each namespace |
| 1027 | where they occur if that is desired. |
| 1028 | |
| 1029 | There are a number of other caveats: |
| 1030 | |
| 1031 | If a module is syntactically correct but its initialization fails, the first |
| 1032 | :keyword:`import` statement for it does not bind its name locally, but does |
| 1033 | store a (partially initialized) module object in ``sys.modules``. To reload the |
| 1034 | module you must first :keyword:`import` it again (this will bind the name to the |
| 1035 | partially initialized module object) before you can :func:`reload` it. |
| 1036 | |
| 1037 | When a module is reloaded, its dictionary (containing the module's global |
| 1038 | variables) is retained. Redefinitions of names will override the old |
| 1039 | definitions, so this is generally not a problem. If the new version of a module |
| 1040 | does not define a name that was defined by the old version, the old definition |
| 1041 | remains. This feature can be used to the module's advantage if it maintains a |
| 1042 | global table or cache of objects --- with a :keyword:`try` statement it can test |
| 1043 | for the table's presence and skip its initialization if desired:: |
| 1044 | |
| 1045 | try: |
| 1046 | cache |
| 1047 | except NameError: |
| 1048 | cache = {} |
| 1049 | |
| 1050 | It is legal though generally not very useful to reload built-in or dynamically |
| 1051 | loaded modules, except for :mod:`sys`, :mod:`__main__` and :mod:`__builtin__`. |
| 1052 | In many cases, however, extension modules are not designed to be initialized |
| 1053 | more than once, and may fail in arbitrary ways when reloaded. |
| 1054 | |
| 1055 | If a module imports objects from another module using :keyword:`from` ... |
| 1056 | :keyword:`import` ..., calling :func:`reload` for the other module does not |
| 1057 | redefine the objects imported from it --- one way around this is to re-execute |
| 1058 | the :keyword:`from` statement, another is to use :keyword:`import` and qualified |
| 1059 | names (*module*.*name*) instead. |
| 1060 | |
| 1061 | If a module instantiates instances of a class, reloading the module that defines |
| 1062 | the class does not affect the method definitions of the instances --- they |
| 1063 | continue to use the old class definition. The same is true for derived classes. |
| 1064 | |
| 1065 | |
| 1066 | .. function:: repr(object) |
| 1067 | |
Georg Brandl | 18f1914 | 2008-03-25 07:20:15 +0000 | [diff] [blame] | 1068 | Return a string containing a printable representation of an object. This is |
| 1069 | the same value yielded by conversions (reverse quotes). It is sometimes |
| 1070 | useful to be able to access this operation as an ordinary function. For many |
| 1071 | types, this function makes an attempt to return a string that would yield an |
| 1072 | object with the same value when passed to :func:`eval`, otherwise the |
| 1073 | representation is a string enclosed in angle brackets that contains the name |
| 1074 | of the type of the object together with additional information often |
| 1075 | including the name and address of the object. A class can control what this |
| 1076 | function returns for its instances by defining a :meth:`__repr__` method. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1077 | |
| 1078 | |
| 1079 | .. function:: reversed(seq) |
| 1080 | |
Georg Brandl | 81de0d2 | 2008-01-06 16:17:56 +0000 | [diff] [blame] | 1081 | Return a reverse :term:`iterator`. *seq* must be an object which has |
| 1082 | a :meth:`__reversed__` method or supports the sequence protocol (the |
| 1083 | :meth:`__len__` method and the :meth:`__getitem__` method with integer |
| 1084 | arguments starting at ``0``). |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1085 | |
| 1086 | .. versionadded:: 2.4 |
| 1087 | |
Georg Brandl | 81de0d2 | 2008-01-06 16:17:56 +0000 | [diff] [blame] | 1088 | .. versionchanged:: 2.6 |
| 1089 | Added the possibility to write a custom :meth:`__reversed__` method. |
| 1090 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1091 | |
| 1092 | .. function:: round(x[, n]) |
| 1093 | |
| 1094 | Return the floating point value *x* rounded to *n* digits after the decimal |
Jeffrey Yasskin | 9871d8f | 2008-01-05 08:47:13 +0000 | [diff] [blame] | 1095 | point. If *n* is omitted, it defaults to zero. The result is a floating point |
| 1096 | number. Values are rounded to the closest multiple of 10 to the power minus |
| 1097 | *n*; if two multiples are equally close, rounding is done away from 0 (so. for |
| 1098 | example, ``round(0.5)`` is ``1.0`` and ``round(-0.5)`` is ``-1.0``). |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1099 | |
| 1100 | |
Mark Dickinson | 19746cb | 2010-07-30 13:16:07 +0000 | [diff] [blame] | 1101 | .. note:: |
| 1102 | |
| 1103 | The behavior of :func:`round` for floats can be surprising: for example, |
| 1104 | ``round(2.675, 2)`` gives ``2.67`` instead of the expected ``2.68``. |
| 1105 | This is not a bug: it's a result of the fact that most decimal fractions |
| 1106 | can't be represented exactly as a float. See :ref:`tut-fp-issues` for |
| 1107 | more information. |
| 1108 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1109 | .. function:: set([iterable]) |
| 1110 | :noindex: |
| 1111 | |
Georg Brandl | 2600a33 | 2009-11-26 20:48:25 +0000 | [diff] [blame] | 1112 | Return a new set, optionally with elements taken from *iterable*. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1113 | The set type is described in :ref:`types-set`. |
| 1114 | |
| 1115 | For other containers see the built in :class:`dict`, :class:`list`, and |
| 1116 | :class:`tuple` classes, and the :mod:`collections` module. |
| 1117 | |
| 1118 | .. versionadded:: 2.4 |
| 1119 | |
| 1120 | |
| 1121 | .. function:: setattr(object, name, value) |
| 1122 | |
| 1123 | This is the counterpart of :func:`getattr`. The arguments are an object, a |
| 1124 | string and an arbitrary value. The string may name an existing attribute or a |
| 1125 | new attribute. The function assigns the value to the attribute, provided the |
| 1126 | object allows it. For example, ``setattr(x, 'foobar', 123)`` is equivalent to |
| 1127 | ``x.foobar = 123``. |
| 1128 | |
| 1129 | |
| 1130 | .. function:: slice([start,] stop[, step]) |
| 1131 | |
| 1132 | .. index:: single: Numerical Python |
| 1133 | |
Georg Brandl | 584265b | 2007-12-02 14:58:50 +0000 | [diff] [blame] | 1134 | Return a :term:`slice` object representing the set of indices specified by |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1135 | ``range(start, stop, step)``. The *start* and *step* arguments default to |
| 1136 | ``None``. Slice objects have read-only data attributes :attr:`start`, |
| 1137 | :attr:`stop` and :attr:`step` which merely return the argument values (or their |
| 1138 | default). They have no other explicit functionality; however they are used by |
| 1139 | Numerical Python and other third party extensions. Slice objects are also |
| 1140 | generated when extended indexing syntax is used. For example: |
Raymond Hettinger | f9bce83 | 2009-02-19 05:34:35 +0000 | [diff] [blame] | 1141 | ``a[start:stop:step]`` or ``a[start:stop, i]``. See :func:`itertools.islice` |
| 1142 | for an alternate version that returns an iterator. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1143 | |
| 1144 | |
| 1145 | .. function:: sorted(iterable[, cmp[, key[, reverse]]]) |
| 1146 | |
| 1147 | Return a new sorted list from the items in *iterable*. |
| 1148 | |
| 1149 | The optional arguments *cmp*, *key*, and *reverse* have the same meaning as |
| 1150 | those for the :meth:`list.sort` method (described in section |
| 1151 | :ref:`typesseq-mutable`). |
| 1152 | |
| 1153 | *cmp* specifies a custom comparison function of two arguments (iterable |
| 1154 | elements) which should return a negative, zero or positive number depending on |
| 1155 | whether the first argument is considered smaller than, equal to, or larger than |
Georg Brandl | a8cbad3 | 2008-01-06 15:34:57 +0000 | [diff] [blame] | 1156 | the second argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``. The default |
| 1157 | value is ``None``. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1158 | |
| 1159 | *key* specifies a function of one argument that is used to extract a comparison |
Georg Brandl | 118c557 | 2010-03-21 09:01:27 +0000 | [diff] [blame] | 1160 | key from each list element: ``key=str.lower``. The default value is ``None`` |
| 1161 | (compare the elements directly). |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1162 | |
| 1163 | *reverse* is a boolean value. If set to ``True``, then the list elements are |
| 1164 | sorted as if each comparison were reversed. |
| 1165 | |
Raymond Hettinger | 749e6d0 | 2009-02-19 06:55:03 +0000 | [diff] [blame] | 1166 | In general, the *key* and *reverse* conversion processes are much faster |
| 1167 | than specifying an equivalent *cmp* function. This is because *cmp* is |
| 1168 | called multiple times for each list element while *key* and *reverse* touch |
Raymond Hettinger | bb006cf | 2010-04-04 21:45:01 +0000 | [diff] [blame] | 1169 | each element only once. Use :func:`functools.cmp_to_key` to convert an |
| 1170 | old-style *cmp* function to a *key* function. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1171 | |
Raymond Hettinger | f54c268 | 2010-04-01 07:54:16 +0000 | [diff] [blame] | 1172 | For sorting examples and a brief sorting tutorial, see `Sorting HowTo |
| 1173 | <http://wiki.python.org/moin/HowTo/Sorting/>`_\. |
| 1174 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1175 | .. versionadded:: 2.4 |
| 1176 | |
| 1177 | |
| 1178 | .. function:: staticmethod(function) |
| 1179 | |
| 1180 | Return a static method for *function*. |
| 1181 | |
| 1182 | A static method does not receive an implicit first argument. To declare a static |
| 1183 | method, use this idiom:: |
| 1184 | |
| 1185 | class C: |
| 1186 | @staticmethod |
| 1187 | def f(arg1, arg2, ...): ... |
| 1188 | |
Georg Brandl | 584265b | 2007-12-02 14:58:50 +0000 | [diff] [blame] | 1189 | The ``@staticmethod`` form is a function :term:`decorator` -- see the |
| 1190 | description of function definitions in :ref:`function` for details. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1191 | |
| 1192 | It can be called either on the class (such as ``C.f()``) or on an instance (such |
| 1193 | as ``C().f()``). The instance is ignored except for its class. |
| 1194 | |
| 1195 | Static methods in Python are similar to those found in Java or C++. For a more |
| 1196 | advanced concept, see :func:`classmethod` in this section. |
| 1197 | |
| 1198 | For more information on static methods, consult the documentation on the |
| 1199 | standard type hierarchy in :ref:`types`. |
| 1200 | |
| 1201 | .. versionadded:: 2.2 |
| 1202 | |
| 1203 | .. versionchanged:: 2.4 |
| 1204 | Function decorator syntax added. |
| 1205 | |
| 1206 | |
| 1207 | .. function:: str([object]) |
| 1208 | |
| 1209 | Return a string containing a nicely printable representation of an object. For |
| 1210 | strings, this returns the string itself. The difference with ``repr(object)`` |
| 1211 | is that ``str(object)`` does not always attempt to return a string that is |
| 1212 | acceptable to :func:`eval`; its goal is to return a printable string. If no |
| 1213 | argument is given, returns the empty string, ``''``. |
| 1214 | |
| 1215 | For more information on strings see :ref:`typesseq` which describes sequence |
| 1216 | functionality (strings are sequences), and also the string-specific methods |
| 1217 | described in the :ref:`string-methods` section. To output formatted strings |
| 1218 | use template strings or the ``%`` operator described in the |
| 1219 | :ref:`string-formatting` section. In addition see the :ref:`stringservices` |
| 1220 | section. See also :func:`unicode`. |
| 1221 | |
| 1222 | |
| 1223 | .. function:: sum(iterable[, start]) |
| 1224 | |
| 1225 | Sums *start* and the items of an *iterable* from left to right and returns the |
| 1226 | total. *start* defaults to ``0``. The *iterable*'s items are normally numbers, |
| 1227 | and are not allowed to be strings. The fast, correct way to concatenate a |
| 1228 | sequence of strings is by calling ``''.join(sequence)``. Note that |
| 1229 | ``sum(range(n), m)`` is equivalent to ``reduce(operator.add, range(n), m)`` |
Raymond Hettinger | f9bce83 | 2009-02-19 05:34:35 +0000 | [diff] [blame] | 1230 | To add floating point values with extended precision, see :func:`math.fsum`\. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1231 | |
| 1232 | .. versionadded:: 2.3 |
| 1233 | |
| 1234 | |
| 1235 | .. function:: super(type[, object-or-type]) |
| 1236 | |
Raymond Hettinger | 9766033 | 2009-02-25 00:37:57 +0000 | [diff] [blame] | 1237 | Return a proxy object that delegates method calls to a parent or sibling |
| 1238 | class of *type*. This is useful for accessing inherited methods that have |
| 1239 | been overridden in a class. The search order is same as that used by |
| 1240 | :func:`getattr` except that the *type* itself is skipped. |
Raymond Hettinger | 3134f14 | 2008-09-19 08:07:48 +0000 | [diff] [blame] | 1241 | |
Raymond Hettinger | b762d58 | 2009-02-25 00:52:37 +0000 | [diff] [blame] | 1242 | The :attr:`__mro__` attribute of the *type* lists the method resolution |
| 1243 | search order used by both :func:`getattr` and :func:`super`. The attribute |
| 1244 | is dynamic and can change whenever the inheritance hierarchy is updated. |
Raymond Hettinger | 9766033 | 2009-02-25 00:37:57 +0000 | [diff] [blame] | 1245 | |
| 1246 | If the second argument is omitted, the super object returned is unbound. If |
| 1247 | the second argument is an object, ``isinstance(obj, type)`` must be true. If |
| 1248 | the second argument is a type, ``issubclass(type2, type)`` must be true (this |
| 1249 | is useful for classmethods). |
Georg Brandl | 95f8ef2 | 2009-02-07 18:49:54 +0000 | [diff] [blame] | 1250 | |
| 1251 | .. note:: |
| 1252 | :func:`super` only works for :term:`new-style class`\es. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1253 | |
Raymond Hettinger | b762d58 | 2009-02-25 00:52:37 +0000 | [diff] [blame] | 1254 | There are two typical use cases for *super*. In a class hierarchy with |
| 1255 | single inheritance, *super* can be used to refer to parent classes without |
Raymond Hettinger | 3134f14 | 2008-09-19 08:07:48 +0000 | [diff] [blame] | 1256 | naming them explicitly, thus making the code more maintainable. This use |
Raymond Hettinger | b762d58 | 2009-02-25 00:52:37 +0000 | [diff] [blame] | 1257 | closely parallels the use of *super* in other programming languages. |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1258 | |
Raymond Hettinger | 9766033 | 2009-02-25 00:37:57 +0000 | [diff] [blame] | 1259 | The second use case is to support cooperative multiple inheritance in a |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1260 | dynamic execution environment. This use case is unique to Python and is |
| 1261 | not found in statically compiled languages or languages that only support |
Raymond Hettinger | ed955f1 | 2009-02-26 00:05:24 +0000 | [diff] [blame] | 1262 | single inheritance. This makes it possible to implement "diamond diagrams" |
Raymond Hettinger | 3134f14 | 2008-09-19 08:07:48 +0000 | [diff] [blame] | 1263 | where multiple base classes implement the same method. Good design dictates |
| 1264 | that this method have the same calling signature in every case (because the |
Raymond Hettinger | 9766033 | 2009-02-25 00:37:57 +0000 | [diff] [blame] | 1265 | order of calls is determined at runtime, because that order adapts |
| 1266 | to changes in the class hierarchy, and because that order can include |
| 1267 | sibling classes that are unknown prior to runtime). |
Raymond Hettinger | 3134f14 | 2008-09-19 08:07:48 +0000 | [diff] [blame] | 1268 | |
| 1269 | For both use cases, a typical superclass call looks like this:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1270 | |
| 1271 | class C(B): |
Raymond Hettinger | 9766033 | 2009-02-25 00:37:57 +0000 | [diff] [blame] | 1272 | def method(self, arg): |
Raymond Hettinger | eb7cbb9 | 2009-02-25 00:39:47 +0000 | [diff] [blame] | 1273 | super(C, self).method(arg) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1274 | |
| 1275 | Note that :func:`super` is implemented as part of the binding process for |
Raymond Hettinger | 9766033 | 2009-02-25 00:37:57 +0000 | [diff] [blame] | 1276 | explicit dotted attribute lookups such as ``super().__getitem__(name)``. |
Raymond Hettinger | 3134f14 | 2008-09-19 08:07:48 +0000 | [diff] [blame] | 1277 | It does so by implementing its own :meth:`__getattribute__` method for searching |
Raymond Hettinger | 9766033 | 2009-02-25 00:37:57 +0000 | [diff] [blame] | 1278 | classes in a predictable order that supports cooperative multiple inheritance. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1279 | Accordingly, :func:`super` is undefined for implicit lookups using statements or |
Raymond Hettinger | 9766033 | 2009-02-25 00:37:57 +0000 | [diff] [blame] | 1280 | operators such as ``super()[name]``. |
| 1281 | |
| 1282 | Also note that :func:`super` is not limited to use inside methods. The two |
| 1283 | argument form specifies the arguments exactly and makes the appropriate |
Raymond Hettinger | afe496d | 2009-02-25 01:06:52 +0000 | [diff] [blame] | 1284 | references. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1285 | |
| 1286 | .. versionadded:: 2.2 |
| 1287 | |
| 1288 | |
| 1289 | .. function:: tuple([iterable]) |
| 1290 | |
| 1291 | Return a tuple whose items are the same and in the same order as *iterable*'s |
| 1292 | items. *iterable* may be a sequence, a container that supports iteration, or an |
| 1293 | iterator object. If *iterable* is already a tuple, it is returned unchanged. |
| 1294 | For instance, ``tuple('abc')`` returns ``('a', 'b', 'c')`` and ``tuple([1, 2, |
| 1295 | 3])`` returns ``(1, 2, 3)``. If no argument is given, returns a new empty |
| 1296 | tuple, ``()``. |
| 1297 | |
| 1298 | :class:`tuple` is an immutable sequence type, as documented in |
| 1299 | :ref:`typesseq`. For other containers see the built in :class:`dict`, |
| 1300 | :class:`list`, and :class:`set` classes, and the :mod:`collections` module. |
| 1301 | |
| 1302 | |
| 1303 | .. function:: type(object) |
| 1304 | |
| 1305 | .. index:: object: type |
| 1306 | |
| 1307 | Return the type of an *object*. The return value is a type object. The |
| 1308 | :func:`isinstance` built-in function is recommended for testing the type of an |
| 1309 | object. |
| 1310 | |
| 1311 | With three arguments, :func:`type` functions as a constructor as detailed below. |
| 1312 | |
| 1313 | |
| 1314 | .. function:: type(name, bases, dict) |
| 1315 | :noindex: |
| 1316 | |
| 1317 | Return a new type object. This is essentially a dynamic form of the |
| 1318 | :keyword:`class` statement. The *name* string is the class name and becomes the |
| 1319 | :attr:`__name__` attribute; the *bases* tuple itemizes the base classes and |
| 1320 | becomes the :attr:`__bases__` attribute; and the *dict* dictionary is the |
| 1321 | namespace containing definitions for class body and becomes the :attr:`__dict__` |
| 1322 | attribute. For example, the following two statements create identical |
Georg Brandl | 7a45ab8 | 2008-03-22 21:38:33 +0000 | [diff] [blame] | 1323 | :class:`type` objects: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1324 | |
| 1325 | >>> class X(object): |
| 1326 | ... a = 1 |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1327 | ... |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1328 | >>> X = type('X', (object,), dict(a=1)) |
| 1329 | |
| 1330 | .. versionadded:: 2.2 |
| 1331 | |
| 1332 | |
| 1333 | .. function:: unichr(i) |
| 1334 | |
| 1335 | Return the Unicode string of one character whose Unicode code is the integer |
| 1336 | *i*. For example, ``unichr(97)`` returns the string ``u'a'``. This is the |
| 1337 | inverse of :func:`ord` for Unicode strings. The valid range for the argument |
| 1338 | depends how Python was configured -- it may be either UCS2 [0..0xFFFF] or UCS4 |
| 1339 | [0..0x10FFFF]. :exc:`ValueError` is raised otherwise. For ASCII and 8-bit |
| 1340 | strings see :func:`chr`. |
| 1341 | |
| 1342 | .. versionadded:: 2.0 |
| 1343 | |
| 1344 | |
| 1345 | .. function:: unicode([object[, encoding [, errors]]]) |
| 1346 | |
| 1347 | Return the Unicode string version of *object* using one of the following modes: |
| 1348 | |
| 1349 | If *encoding* and/or *errors* are given, ``unicode()`` will decode the object |
| 1350 | which can either be an 8-bit string or a character buffer using the codec for |
| 1351 | *encoding*. The *encoding* parameter is a string giving the name of an encoding; |
| 1352 | if the encoding is not known, :exc:`LookupError` is raised. Error handling is |
| 1353 | done according to *errors*; this specifies the treatment of characters which are |
| 1354 | invalid in the input encoding. If *errors* is ``'strict'`` (the default), a |
| 1355 | :exc:`ValueError` is raised on errors, while a value of ``'ignore'`` causes |
| 1356 | errors to be silently ignored, and a value of ``'replace'`` causes the official |
| 1357 | Unicode replacement character, ``U+FFFD``, to be used to replace input |
| 1358 | characters which cannot be decoded. See also the :mod:`codecs` module. |
| 1359 | |
| 1360 | If no optional parameters are given, ``unicode()`` will mimic the behaviour of |
| 1361 | ``str()`` except that it returns Unicode strings instead of 8-bit strings. More |
| 1362 | precisely, if *object* is a Unicode string or subclass it will return that |
| 1363 | Unicode string without any additional decoding applied. |
| 1364 | |
| 1365 | For objects which provide a :meth:`__unicode__` method, it will call this method |
| 1366 | without arguments to create a Unicode string. For all other objects, the 8-bit |
| 1367 | string version or representation is requested and then converted to a Unicode |
| 1368 | string using the codec for the default encoding in ``'strict'`` mode. |
| 1369 | |
| 1370 | For more information on Unicode strings see :ref:`typesseq` which describes |
| 1371 | sequence functionality (Unicode strings are sequences), and also the |
| 1372 | string-specific methods described in the :ref:`string-methods` section. To |
| 1373 | output formatted strings use template strings or the ``%`` operator described |
| 1374 | in the :ref:`string-formatting` section. In addition see the |
| 1375 | :ref:`stringservices` section. See also :func:`str`. |
| 1376 | |
| 1377 | .. versionadded:: 2.0 |
| 1378 | |
| 1379 | .. versionchanged:: 2.2 |
| 1380 | Support for :meth:`__unicode__` added. |
| 1381 | |
| 1382 | |
| 1383 | .. function:: vars([object]) |
| 1384 | |
Georg Brandl | 54967d9 | 2009-09-18 21:21:41 +0000 | [diff] [blame] | 1385 | Without an argument, act like :func:`locals`. |
| 1386 | |
| 1387 | With a module, class or class instance object as argument (or anything else that |
| 1388 | has a :attr:`__dict__` attribute), return that attribute. |
Georg Brandl | d59efbc | 2009-03-30 22:09:34 +0000 | [diff] [blame] | 1389 | |
Georg Brandl | 16a57f6 | 2009-04-27 15:29:09 +0000 | [diff] [blame] | 1390 | .. note:: |
Georg Brandl | d59efbc | 2009-03-30 22:09:34 +0000 | [diff] [blame] | 1391 | |
| 1392 | The returned dictionary should not be modified: |
| 1393 | the effects on the corresponding symbol table are undefined. [#]_ |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1394 | |
| 1395 | |
| 1396 | .. function:: xrange([start,] stop[, step]) |
| 1397 | |
| 1398 | This function is very similar to :func:`range`, but returns an "xrange object" |
| 1399 | instead of a list. This is an opaque sequence type which yields the same values |
| 1400 | as the corresponding list, without actually storing them all simultaneously. |
| 1401 | The advantage of :func:`xrange` over :func:`range` is minimal (since |
| 1402 | :func:`xrange` still has to create the values when asked for them) except when a |
| 1403 | very large range is used on a memory-starved machine or when all of the range's |
| 1404 | elements are never used (such as when the loop is usually terminated with |
| 1405 | :keyword:`break`). |
| 1406 | |
Georg Brandl | 6c14e58 | 2009-10-22 11:48:10 +0000 | [diff] [blame] | 1407 | .. impl-detail:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1408 | |
Georg Brandl | 6c14e58 | 2009-10-22 11:48:10 +0000 | [diff] [blame] | 1409 | :func:`xrange` is intended to be simple and fast. Implementations may |
| 1410 | impose restrictions to achieve this. The C implementation of Python |
| 1411 | restricts all arguments to native C longs ("short" Python integers), and |
| 1412 | also requires that the number of elements fit in a native C long. If a |
| 1413 | larger range is needed, an alternate version can be crafted using the |
| 1414 | :mod:`itertools` module: ``islice(count(start, step), |
| 1415 | (stop-start+step-1)//step)``. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1416 | |
| 1417 | |
| 1418 | .. function:: zip([iterable, ...]) |
| 1419 | |
| 1420 | This function returns a list of tuples, where the *i*-th tuple contains the |
| 1421 | *i*-th element from each of the argument sequences or iterables. The returned |
| 1422 | list is truncated in length to the length of the shortest argument sequence. |
| 1423 | When there are multiple arguments which are all of the same length, :func:`zip` |
| 1424 | is similar to :func:`map` with an initial argument of ``None``. With a single |
| 1425 | sequence argument, it returns a list of 1-tuples. With no arguments, it returns |
| 1426 | an empty list. |
| 1427 | |
Raymond Hettinger | 9ed5b57 | 2008-01-22 20:18:53 +0000 | [diff] [blame] | 1428 | The left-to-right evaluation order of the iterables is guaranteed. This |
| 1429 | makes possible an idiom for clustering a data series into n-length groups |
| 1430 | using ``zip(*[iter(s)]*n)``. |
| 1431 | |
Benjamin Peterson | 83ca0a6 | 2008-10-10 20:51:37 +0000 | [diff] [blame] | 1432 | :func:`zip` in conjunction with the ``*`` operator can be used to unzip a |
| 1433 | list:: |
| 1434 | |
| 1435 | >>> x = [1, 2, 3] |
| 1436 | >>> y = [4, 5, 6] |
| 1437 | >>> zipped = zip(x, y) |
| 1438 | >>> zipped |
| 1439 | [(1, 4), (2, 5), (3, 6)] |
| 1440 | >>> x2, y2 = zip(*zipped) |
Georg Brandl | fa0123b | 2009-05-22 09:33:25 +0000 | [diff] [blame] | 1441 | >>> x == list(x2) and y == list(y2) |
Benjamin Peterson | 83ca0a6 | 2008-10-10 20:51:37 +0000 | [diff] [blame] | 1442 | True |
| 1443 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1444 | .. versionadded:: 2.0 |
| 1445 | |
| 1446 | .. versionchanged:: 2.4 |
| 1447 | Formerly, :func:`zip` required at least one argument and ``zip()`` raised a |
| 1448 | :exc:`TypeError` instead of returning an empty list. |
| 1449 | |
Georg Brandl | 248e172 | 2008-12-05 15:52:20 +0000 | [diff] [blame] | 1450 | |
| 1451 | .. function:: __import__(name[, globals[, locals[, fromlist[, level]]]]) |
| 1452 | |
| 1453 | .. index:: |
| 1454 | statement: import |
Georg Brandl | 248e172 | 2008-12-05 15:52:20 +0000 | [diff] [blame] | 1455 | module: imp |
| 1456 | |
| 1457 | .. note:: |
| 1458 | |
| 1459 | This is an advanced function that is not needed in everyday Python |
| 1460 | programming. |
| 1461 | |
Georg Brandl | f8668ce | 2008-12-07 22:42:09 +0000 | [diff] [blame] | 1462 | This function is invoked by the :keyword:`import` statement. It can be |
Georg Brandl | c9a8a4a | 2010-04-14 21:36:49 +0000 | [diff] [blame] | 1463 | replaced (by importing the :mod:`__builtin__` module and assigning to |
| 1464 | ``__builtin__.__import__``) in order to change semantics of the |
Georg Brandl | f8668ce | 2008-12-07 22:42:09 +0000 | [diff] [blame] | 1465 | :keyword:`import` statement, but nowadays it is usually simpler to use import |
| 1466 | hooks (see :pep:`302`). Direct use of :func:`__import__` is rare, except in |
| 1467 | cases where you want to import a module whose name is only known at runtime. |
Georg Brandl | 248e172 | 2008-12-05 15:52:20 +0000 | [diff] [blame] | 1468 | |
Georg Brandl | f8668ce | 2008-12-07 22:42:09 +0000 | [diff] [blame] | 1469 | The function imports the module *name*, potentially using the given *globals* |
| 1470 | and *locals* to determine how to interpret the name in a package context. |
| 1471 | The *fromlist* gives the names of objects or submodules that should be |
| 1472 | imported from the module given by *name*. The standard implementation does |
| 1473 | not use its *locals* argument at all, and uses its *globals* only to |
| 1474 | determine the package context of the :keyword:`import` statement. |
| 1475 | |
| 1476 | *level* specifies whether to use absolute or relative imports. The default |
| 1477 | is ``-1`` which indicates both absolute and relative imports will be |
| 1478 | attempted. ``0`` means only perform absolute imports. Positive values for |
| 1479 | *level* indicate the number of parent directories to search relative to the |
| 1480 | directory of the module calling :func:`__import__`. |
Georg Brandl | 248e172 | 2008-12-05 15:52:20 +0000 | [diff] [blame] | 1481 | |
| 1482 | When the *name* variable is of the form ``package.module``, normally, the |
| 1483 | top-level package (the name up till the first dot) is returned, *not* the |
| 1484 | module named by *name*. However, when a non-empty *fromlist* argument is |
Georg Brandl | f8668ce | 2008-12-07 22:42:09 +0000 | [diff] [blame] | 1485 | given, the module named by *name* is returned. |
Georg Brandl | 248e172 | 2008-12-05 15:52:20 +0000 | [diff] [blame] | 1486 | |
Georg Brandl | f8668ce | 2008-12-07 22:42:09 +0000 | [diff] [blame] | 1487 | For example, the statement ``import spam`` results in bytecode resembling the |
| 1488 | following code:: |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1489 | |
Georg Brandl | f8668ce | 2008-12-07 22:42:09 +0000 | [diff] [blame] | 1490 | spam = __import__('spam', globals(), locals(), [], -1) |
Georg Brandl | 248e172 | 2008-12-05 15:52:20 +0000 | [diff] [blame] | 1491 | |
Georg Brandl | f8668ce | 2008-12-07 22:42:09 +0000 | [diff] [blame] | 1492 | The statement ``import spam.ham`` results in this call:: |
| 1493 | |
| 1494 | spam = __import__('spam.ham', globals(), locals(), [], -1) |
| 1495 | |
| 1496 | Note how :func:`__import__` returns the toplevel module here because this is |
| 1497 | the object that is bound to a name by the :keyword:`import` statement. |
| 1498 | |
| 1499 | On the other hand, the statement ``from spam.ham import eggs, sausage as |
| 1500 | saus`` results in :: |
| 1501 | |
| 1502 | _temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1) |
| 1503 | eggs = _temp.eggs |
| 1504 | saus = _temp.sausage |
| 1505 | |
| 1506 | Here, the ``spam.ham`` module is returned from :func:`__import__`. From this |
| 1507 | object, the names to import are retrieved and assigned to their respective |
| 1508 | names. |
| 1509 | |
| 1510 | If you simply want to import a module (potentially within a package) by name, |
Georg Brandl | e15048e | 2009-05-22 09:50:30 +0000 | [diff] [blame] | 1511 | you can call :func:`__import__` and then look it up in :data:`sys.modules`:: |
Georg Brandl | f8668ce | 2008-12-07 22:42:09 +0000 | [diff] [blame] | 1512 | |
| 1513 | >>> import sys |
| 1514 | >>> name = 'foo.bar.baz' |
| 1515 | >>> __import__(name) |
| 1516 | <module 'foo' from ...> |
| 1517 | >>> baz = sys.modules[name] |
| 1518 | >>> baz |
| 1519 | <module 'foo.bar.baz' from ...> |
Georg Brandl | 248e172 | 2008-12-05 15:52:20 +0000 | [diff] [blame] | 1520 | |
| 1521 | .. versionchanged:: 2.5 |
| 1522 | The level parameter was added. |
| 1523 | |
| 1524 | .. versionchanged:: 2.5 |
| 1525 | Keyword support for parameters was added. |
| 1526 | |
Georg Brandl | 4273222 | 2008-01-06 23:22:27 +0000 | [diff] [blame] | 1527 | .. --------------------------------------------------------------------------- |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1528 | |
| 1529 | |
| 1530 | .. _non-essential-built-in-funcs: |
| 1531 | |
| 1532 | Non-essential Built-in Functions |
| 1533 | ================================ |
| 1534 | |
| 1535 | There are several built-in functions that are no longer essential to learn, know |
| 1536 | or use in modern Python programming. They have been kept here to maintain |
| 1537 | backwards compatibility with programs written for older versions of Python. |
| 1538 | |
Benjamin Peterson | 90f3673 | 2008-07-12 20:16:19 +0000 | [diff] [blame] | 1539 | Python programmers, trainers, students and book writers should feel free to |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1540 | bypass these functions without concerns about missing something important. |
| 1541 | |
| 1542 | |
| 1543 | .. function:: apply(function, args[, keywords]) |
| 1544 | |
| 1545 | The *function* argument must be a callable object (a user-defined or built-in |
| 1546 | function or method, or a class object) and the *args* argument must be a |
| 1547 | sequence. The *function* is called with *args* as the argument list; the number |
| 1548 | of arguments is the length of the tuple. If the optional *keywords* argument is |
| 1549 | present, it must be a dictionary whose keys are strings. It specifies keyword |
| 1550 | arguments to be added to the end of the argument list. Calling :func:`apply` is |
| 1551 | different from just calling ``function(args)``, since in that case there is |
Georg Brandl | a3bb57c | 2008-04-26 18:25:43 +0000 | [diff] [blame] | 1552 | always exactly one argument. The use of :func:`apply` is equivalent to |
Georg Brandl | c4ed971 | 2007-10-19 12:32:39 +0000 | [diff] [blame] | 1553 | ``function(*args, **keywords)``. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1554 | |
| 1555 | .. deprecated:: 2.3 |
Georg Brandl | c4ed971 | 2007-10-19 12:32:39 +0000 | [diff] [blame] | 1556 | Use the extended call syntax with ``*args`` and ``**keywords`` instead. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1557 | |
| 1558 | |
| 1559 | .. function:: buffer(object[, offset[, size]]) |
| 1560 | |
| 1561 | The *object* argument must be an object that supports the buffer call interface |
| 1562 | (such as strings, arrays, and buffers). A new buffer object will be created |
| 1563 | which references the *object* argument. The buffer object will be a slice from |
| 1564 | the beginning of *object* (or from the specified *offset*). The slice will |
| 1565 | extend to the end of *object* (or will have a length given by the *size* |
| 1566 | argument). |
| 1567 | |
| 1568 | |
| 1569 | .. function:: coerce(x, y) |
| 1570 | |
| 1571 | Return a tuple consisting of the two numeric arguments converted to a common |
| 1572 | type, using the same rules as used by arithmetic operations. If coercion is not |
| 1573 | possible, raise :exc:`TypeError`. |
| 1574 | |
| 1575 | |
| 1576 | .. function:: intern(string) |
| 1577 | |
| 1578 | Enter *string* in the table of "interned" strings and return the interned string |
| 1579 | -- which is *string* itself or a copy. Interning strings is useful to gain a |
| 1580 | little performance on dictionary lookup -- if the keys in a dictionary are |
| 1581 | interned, and the lookup key is interned, the key comparisons (after hashing) |
| 1582 | can be done by a pointer compare instead of a string compare. Normally, the |
| 1583 | names used in Python programs are automatically interned, and the dictionaries |
| 1584 | used to hold module, class or instance attributes have interned keys. |
| 1585 | |
| 1586 | .. versionchanged:: 2.3 |
| 1587 | Interned strings are not immortal (like they used to be in Python 2.2 and |
| 1588 | before); you must keep a reference to the return value of :func:`intern` around |
| 1589 | to benefit from it. |
| 1590 | |
| 1591 | .. rubric:: Footnotes |
| 1592 | |
| 1593 | .. [#] It is used relatively rarely so does not warrant being made into a statement. |
| 1594 | |
| 1595 | .. [#] Specifying a buffer size currently has no effect on systems that don't have |
| 1596 | :cfunc:`setvbuf`. The interface to specify the buffer size is not done using a |
| 1597 | method that calls :cfunc:`setvbuf`, because that may dump core when called after |
| 1598 | any I/O has been performed, and there's no reliable way to determine whether |
| 1599 | this is the case. |
| 1600 | |
| 1601 | .. [#] In the current implementation, local variable bindings cannot normally be |
| 1602 | affected this way, but variables retrieved from other scopes (such as modules) |
| 1603 | can be. This may change. |
| 1604 | |