| |
| In interactive mode, if the value is not ``None``, it is converted to a string |
| using the built-in :func:`repr` function and the resulting string is written to |
| standard output (see section :ref:`print`) on a line by itself. (Expression |
| statements yielding ``None`` are not written, so that procedure calls do not |
| cause any output.) |
| |
| |
n | .. _assert: |
| |
| Assert statements |
| ================= |
| |
| .. index:: |
| statement: assert |
| pair: debugging; assertions |
| |
| Assert statements are a convenient way to insert debugging assertions into a |
| program: |
| |
| .. productionlist:: |
| assert_stmt: "assert" `expression` ["," `expression`] |
| |
| The simple form, ``assert expression``, is equivalent to :: |
| |
| if __debug__: |
| if not expression: raise AssertionError |
| |
| The extended form, ``assert expression1, expression2``, is equivalent to :: |
| |
| if __debug__: |
| if not expression1: raise AssertionError, expression2 |
| |
| .. index:: |
| single: __debug__ |
| exception: AssertionError |
| |
| These equivalences assume that ``__debug__`` and :exc:`AssertionError` refer to |
| the built-in variables with those names. In the current implementation, the |
| built-in variable ``__debug__`` is ``True`` under normal circumstances, |
| ``False`` when optimization is requested (command line option -O). The current |
| code generator emits no code for an assert statement when optimization is |
| requested at compile time. Note that it is unnecessary to include the source |
| code for the expression that failed in the error message; it will be displayed |
| as part of the stack trace. |
| |
| Assignments to ``__debug__`` are illegal. The value for the built-in variable |
| is determined when the interpreter starts. |
| |
| |
| .. _assignment: |
| |
| Assignment statements |
| ===================== |
| |
| .. index:: |
| pair: assignment; statement |
| pair: binding; name |
| pair: rebinding; name |
| object: mutable |
| pair: attribute; assignment |
| |
| Assignment statements are used to (re)bind names to values and to modify |
| attributes or items of mutable objects: |
| |
| .. productionlist:: |
n | assignment_stmt: (`target_list` "=")+ `expression_list` |
n | assignment_stmt: (`target_list` "=")+ (`expression_list` | `yield_expression`) |
| target_list: `target` ("," `target`)\* [","] |
| target_list: `target` ("," `target`)* [","] |
| target: `identifier` |
n | : \| "(" `target_list` ")" |
n | : | "(" `target_list` ")" |
| : \| "[" `target_list` "]" |
| : | "[" `target_list` "]" |
| : \| `attributeref` |
| : | `attributeref` |
| : \| `subscription` |
| : | `subscription` |
| : \| `slicing` |
| : | `slicing` |
| |
| (See section :ref:`primaries` for the syntax definitions for the last three |
| symbols.) |
| |
| .. index:: pair: expression; list |
| |
| An assignment statement evaluates the expression list (remember that this can be |
| a single expression or a comma-separated list, the latter yielding a tuple) and |
| given with the definition of the object types (see section :ref:`types`). |
| |
| .. index:: triple: target; list; assignment |
| |
| Assignment of an object to a target list is recursively defined as follows. |
| |
| * If the target list is a single target: The object is assigned to that target. |
| |
n | * If the target list is a comma-separated list of targets: The object must be a |
n | * If the target list is a comma-separated list of targets: The object must be an |
| sequence with the same number of items as there are targets in the target list, |
| iterable with the same number of items as there are targets in the target list, |
| and the items are assigned, from left to right, to the corresponding targets. |
| (This rule is relaxed as of Python 1.5; in earlier versions, the object had to |
| be a tuple. Since strings are sequences, an assignment like ``a, b = "xy"`` is |
| now legal as long as the string has the right length.) |
| |
| Assignment of an object to a single target is recursively defined as follows. |
| |
| * If the target is an identifier (name): |
| |
| .. index:: statement: global |
| |
n | * If the name does not occur in a :keyword:`global` statement in the current |
n | * If the name does not occur in a :keyword:`global` statement in the current |
| code block: the name is bound to the object in the current local namespace. |
| |
n | * Otherwise: the name is bound to the object in the current global namespace. |
n | * Otherwise: the name is bound to the object in the current global namespace. |
| |
| .. index:: single: destructor |
| |
| The name is rebound if it was already bound. This may cause the reference count |
| for the object previously bound to the name to reach zero, causing the object to |
| be deallocated and its destructor (if it has one) to be called. |
| |
n | .. % nested |
| |
| * If the target is a target list enclosed in parentheses or in square brackets: |
n | The object must be a sequence with the same number of items as there are targets |
n | The object must be an iterable with the same number of items as there are |
| in the target list, and its items are assigned, from left to right, to the |
| targets in the target list, and its items are assigned, from left to right, |
| corresponding targets. |
| to the corresponding targets. |
| |
| .. index:: pair: attribute; assignment |
| |
| * If the target is an attribute reference: The primary expression in the |
| reference is evaluated. It should yield an object with assignable attributes; |
| if this is not the case, :exc:`TypeError` is raised. That object is then asked |
| to assign the assigned object to the given attribute; if it cannot perform the |
| assignment, it raises an exception (usually but not necessarily |
| instance variable. For example:: |
| |
| class A: |
| x = 3 # class variable |
| a = A() |
| a.x += 1 # writes a.x as 4 leaving A.x as 3 |
| |
| |
n | .. _assert: |
| |
| The :keyword:`assert` statement |
| =============================== |
| |
| .. index:: |
| statement: assert |
| pair: debugging; assertions |
| |
| Assert statements are a convenient way to insert debugging assertions into a |
| program: |
| |
| .. productionlist:: |
| assert_stmt: "assert" `expression` ["," `expression`] |
| |
| The simple form, ``assert expression``, is equivalent to :: |
| |
| if __debug__: |
| if not expression: raise AssertionError |
| |
| The extended form, ``assert expression1, expression2``, is equivalent to :: |
| |
| if __debug__: |
| if not expression1: raise AssertionError, expression2 |
| |
| .. index:: |
| single: __debug__ |
| exception: AssertionError |
| |
| These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to |
| the built-in variables with those names. In the current implementation, the |
| built-in variable :const:`__debug__` is ``True`` under normal circumstances, |
| ``False`` when optimization is requested (command line option -O). The current |
| code generator emits no code for an assert statement when optimization is |
| requested at compile time. Note that it is unnecessary to include the source |
| code for the expression that failed in the error message; it will be displayed |
| as part of the stack trace. |
| |
| Assignments to :const:`__debug__` are illegal. The value for the built-in variable |
| is determined when the interpreter starts. |
| |
| |
| .. _pass: |
| |
| The :keyword:`pass` statement |
| ============================= |
| |
n | .. index:: statement: pass |
n | .. index:: |
| statement: pass |
| pair: null; operation |
| |
| .. productionlist:: |
| pass_stmt: "pass" |
n | |
| .. index:: pair: null; operation |
| |
| :keyword:`pass` is a null operation --- when it is executed, nothing happens. |
| It is useful as a placeholder when a statement is required syntactically, but no |
| code needs to be executed, for example:: |
| |
| def f(arg): pass # a function that does nothing (yet) |
| |
| class C: pass # a class with no methods (yet) |
| |
| |
| .. _del: |
| |
| The :keyword:`del` statement |
| ============================ |
| |
n | .. index:: statement: del |
| |
| .. productionlist:: |
| del_stmt: "del" `target_list` |
| |
| .. index:: |
n | statement: del |
| pair: deletion; target |
| triple: deletion; target; list |
n | |
| .. productionlist:: |
| del_stmt: "del" `target_list` |
| |
| Deletion is recursively defined very similar to the way assignment is defined. |
| Rather that spelling it out in full details, here are some hints. |
| |
| Deletion of a target list recursively deletes each target, from left to right. |
| |
| .. index:: |
| statement: global |
| really leaving the loop. |
| |
| |
| .. _continue: |
| |
| The :keyword:`continue` statement |
| ================================= |
| |
n | .. index:: |
| .. index:: statement: continue |
| statement: continue |
| |
| .. productionlist:: |
| continue_stmt: "continue" |
| |
| .. index:: |
| statement: for |
| statement: while |
| pair: loop; statement |
| keyword: finally |
| |
n | .. productionlist:: |
| continue_stmt: "continue" |
| |
| :keyword:`continue` may only occur syntactically nested in a :keyword:`for` or |
| :keyword:`while` loop, but not nested in a function or class definition or |
n | :keyword:`finally` statement within that loop. [#]_ It continues with the next |
n | :keyword:`finally` clause within that loop. It continues with the next |
| cycle of the nearest enclosing loop. |
| |
n | When :keyword:`continue` passes control out of a :keyword:`try` statement with a |
| :keyword:`finally` clause, that :keyword:`finally` clause is executed before |
| really starting the next loop cycle. |
| |
| |
| .. _import: |
n | .. _from: |
| |
| The :keyword:`import` statement |
| =============================== |
| |
| .. index:: |
| statement: import |
| single: module; importing |
| pair: name; binding |
| keyword: from |
| |
| .. productionlist:: |
n | import_stmt: "import" `module` ["as" `name`] ( "," `module` ["as" `name`] )\* |
n | import_stmt: "import" `module` ["as" `name`] ( "," `module` ["as" `name`] )* |
| : \| "from" `module` "import" `identifier` ["as" `name`] |
| : | "from" `relative_module` "import" `identifier` ["as" `name`] |
| : ( "," `identifier` ["as" `name`] )\* |
| : ( "," `identifier` ["as" `name`] )* |
| : \| "from" `module` "import" "(" `identifier` ["as" `name`] |
| : | "from" `relative_module` "import" "(" `identifier` ["as" `name`] |
| : ( "," `identifier` ["as" `name`] )\* [","] ")" |
| : ( "," `identifier` ["as" `name`] )* [","] ")" |
| : \| "from" `module` "import" "\*" |
| : | "from" `module` "import" "*" |
| module: (`identifier` ".")\* `identifier` |
| module: (`identifier` ".")* `identifier` |
| relative_module: "."* `module` | "."+ |
| name: `identifier` |
| |
| Import statements are executed in two steps: (1) find a module, and initialize |
| it if necessary; (2) define a name or names in the local namespace (of the scope |
n | where the :keyword:`import` statement occurs). The first form (without |
n | where the :keyword:`import` statement occurs). The statement comes in two |
| forms differing on whether it uses the :keyword:`from` keyword. The first form |
| :keyword:`from`) repeats these steps for each identifier in the list. The form |
| (without :keyword:`from`) repeats these steps for each identifier in the list. |
| with :keyword:`from` performs step (1) once, and then performs step (2) |
| The form with :keyword:`from` performs step (1) once, and then performs step |
| repeatedly. |
| (2) repeatedly. |
| |
n | In this context, to "initialize" a built-in or extension module means to call an |
| initialization function that the module must provide for the purpose (in the |
| reference implementation, the function's name is obtained by prepending string |
| "init" to the module's name); to "initialize" a Python-coded module means to |
| execute the module's body. |
| |
| .. index:: |
n | single: modules (in module sys) |
n | single: package |
| |
| To understand how step (1) occurs, one must first understand how Python handles |
| hierarchical naming of modules. To help organize modules and provide a |
| hierarchy in naming, Python has a concept of packages. A package can contain |
| other packages and modules while modules cannot contain other modules or |
| packages. From a file system perspective, packages are directories and modules |
| are files. The original `specification for packages |
| <http://www.python.org/doc/essays/packages.html>`_ is still available to read, |
| although minor details have changed since the writing of that document. |
| |
| .. index:: |
| single: sys.modules |
| single: sys.modules |
| pair: module; name |
| pair: built-in; module |
| pair: user-defined; module |
| module: sys |
| pair: filename; extension |
| triple: module; search; path |
| |
n | The system maintains a table of modules that have been or are being initialized, |
n | Once the name of the module is known (unless otherwise specified, the term |
| indexed by module name. This table is accessible as ``sys.modules``. When a |
| "module" will refer to both packages and modules), searching |
| module name is found in this table, step (1) is finished. If not, a search for |
| for the module or package can begin. The first place checked is |
| a module definition is started. When a module is found, it is loaded. Details |
| :data:`sys.modules`, the cache of all modules that have been imported |
| of the module searching and loading process are implementation and platform |
| previously. If the module is found there then it is used in step (2) of import. |
| specific. It generally involves searching for a "built-in" module with the |
| given name and then searching a list of locations given as ``sys.path``. |
| |
| .. index:: |
n | pair: module; initialization |
n | single: sys.meta_path |
| single: finder |
| pair: finder; find_module |
| single: __path__ |
| |
| If the module is not found in the cache, then :data:`sys.meta_path` is searched |
| (the specification for :data:`sys.meta_path` can be found in :pep:`302`). |
| The object is a list of :term:`finder` objects which are queried in order as to |
| whether they know how to load the module by calling their :meth:`find_module` |
| method with the name of the module. If the module happens to be contained |
| within a package (as denoted by the existence of a dot in the name), then a |
| second argument to :meth:`find_module` is given as the value of the |
| :attr:`__path__` attribute from the parent package (everything up to the last |
| dot in the name of the module being imported). If a finder can find the module |
| it returns a :term:`loader` (discussed later) or returns :keyword:`None`. |
| |
| .. index:: |
| single: sys.path_hooks |
| single: sys.path_importer_cache |
| single: sys.path |
| |
| If none of the finders on :data:`sys.meta_path` are able to find the module |
| then some implicitly defined finders are queried. Implementations of Python |
| vary in what implicit meta path finders are defined. The one they all do |
| define, though, is one that handles :data:`sys.path_hooks`, |
| :data:`sys.path_importer_cache`, and :data:`sys.path`. |
| |
| The implicit finder searches for the requested module in the "paths" specified |
| in one of two places ("paths" do not have to be file system paths). If the |
| module being imported is supposed to be contained within a package then the |
| second argument passed to :meth:`find_module`, :attr:`__path__` on the parent |
| package, is used as the source of paths. If the module is not contained in a |
| package then :data:`sys.path` is used as the source of paths. |
| |
| Once the source of paths is chosen it is iterated over to find a finder that |
| can handle that path. The dict at :data:`sys.path_importer_cache` caches |
| finders for paths and is checked for a finder. If the path does not have a |
| finder cached then :data:`sys.path_hooks` is searched by calling each object in |
| the list with a single argument of the path, returning a finder or raises |
| :exc:`ImportError`. If a finder is returned then it is cached in |
| :data:`sys.path_importer_cache` and then used for that path entry. If no finder |
| can be found but the path exists then a value of :keyword:`None` is |
| stored in :data:`sys.path_importer_cache` to signify that an implicit, |
| file-based finder that handles modules stored as individual files should be |
| used for that path. If the path does not exist then a finder which always |
| returns :keyword:`None` is placed in the cache for the path. |
| |
| .. index:: |
| single: loader |
| pair: loader; load_module |
| exception: ImportError |
| exception: ImportError |
| single: code block |
| |
| If no finder can find the module then :exc:`ImportError` is raised. Otherwise |
| some finder returned a loader whose :meth:`load_module` method is called with |
| the name of the module to load (see :pep:`302` for the original definition of |
| loaders). A loader has several responsibilities to perform on a module it |
| loads. First, if the module already exists in :data:`sys.modules` (a |
| possibility if the loader is called outside of the import machinery) then it |
| is to use that module for initialization and not a new module. But if the |
| module does not exist in :data:`sys.modules` then it is to be added to that |
| dict before initialization begins. If an error occurs during loading of the |
| module and it was added to :data:`sys.modules` it is to be removed from the |
| dict. If an error occurs but the module was already in :data:`sys.modules` it |
| is left in the dict. |
| |
| .. index:: |
| single: __name__ |
| single: __file__ |
| single: __path__ |
| single: __package__ |
| single: __loader__ |
| |
| The loader must set several attributes on the module. :data:`__name__` is to be |
| set to the name of the module. :data:`__file__` is to be the "path" to the file |
| unless the module is built-in (and thus listed in |
| :data:`sys.builtin_module_names`) in which case the attribute is not set. |
| If what is being imported is a package then :data:`__path__` is to be set to a |
| list of paths to be searched when looking for modules and packages contained |
| within the package being imported. :data:`__package__` is optional but should |
| be set to the name of package that contains the module or package (the empty |
| string is used for module not contained in a package). :data:`__loader__` is |
| also optional but should be set to the loader object that is loading the |
| module. |
| |
| .. index:: |
| exception: SyntaxError |
| exception: ImportError |
| |
n | If a built-in module is found, its built-in initialization code is executed and |
n | If an error occurs during loading then the loader raises :exc:`ImportError` if |
| step (1) is finished. If no matching file is found, :exc:`ImportError` is |
| some other exception is not already being propagated. Otherwise the loader |
| raised. If a file is found, it is parsed, yielding an executable code block. If |
| returns the module that was loaded and initialized. |
| a syntax error occurs, :exc:`SyntaxError` is raised. Otherwise, an empty module |
| of the given name is created and inserted in the module table, and then the code |
| block is executed in the context of this module. Exceptions during this |
| execution terminate step (1). |
| |
| When step (1) finishes without raising an exception, step (2) can begin. |
| |
| The first form of :keyword:`import` statement binds the module name in the local |
| namespace to the module object, and then goes on to import the next identifier, |
| if any. If the module name is followed by :keyword:`as`, the name following |
| :keyword:`as` is used as the local name for the module. |
| |
| modules which were imported and used within the module). |
| |
| The :keyword:`from` form with ``*`` may only occur in a module scope. If the |
| wild card form of import --- ``import *`` --- is used in a function and the |
| function contains or is a nested block with free variables, the compiler will |
| raise a :exc:`SyntaxError`. |
| |
| .. index:: |
n | keyword: from |
n | single: relative; import |
| statement: from |
| |
n | .. index:: |
n | When specifying what module to import you do not have to specify the absolute |
| triple: hierarchical; module; names |
| name of the module. When a module or package is contained within another |
| single: packages |
| package it is possible to make a relative import within the same top package |
| single: __init__.py |
| without having to mention the package name. By using leading dots in the |
| specified module or package after :keyword:`from` you can specify how high to |
| traverse up the current package hierarchy without specifying exact names. One |
| leading dot means the current package where the module making the import |
| exists. Two dots means up one package level. Three dots is up two levels, etc. |
| So if you execute ``from . import mod`` from a module in the ``pkg`` package |
| then you will end up importing ``pkg.mod``. If you execute ``from ..subpkg2 |
| imprt mod`` from within ``pkg.subpkg1`` you will import ``pkg.subpkg2.mod``. |
| The specification for relative imports is contained within :pep:`328`. |
| |
n | **Hierarchical module names:** when the module names contains one or more dots, |
| the module search path is carried out differently. The sequence of identifiers |
| up to the last dot is used to find a "package"; the final identifier is then |
| searched inside the package. A package is generally a subdirectory of a |
| directory on ``sys.path`` that has a file :file:`__init__.py`. [XXX Can't be |
| bothered to spell this out right now; see the URL |
| `<http://www.python.org/doc/essays/packages.html>`_ for more details, also about |
| how the module search works from inside a package.] |
| |
| .. % |
| |
| .. index:: builtin: __import__ |
| |
| The built-in function :func:`__import__` is provided to support applications |
n | that determine which modules need to be loaded dynamically; refer to Built-in |
n | that determine which modules need to be loaded dynamically; refer to |
| Functions (XXX reference: ../lib/built-in-funcs.html) in the Python Library |
| :ref:`built-in-funcs` for additional information. |
| Reference (XXX reference: ../lib/lib.html) for additional information. |
| |
| |
| .. _future: |
| |
| Future statements |
| ----------------- |
| |
| .. index:: pair: future; statement |
| A :dfn:`future statement` is a directive to the compiler that a particular |
| module should be compiled using syntax or semantics that will be available in a |
| specified future release of Python. The future statement is intended to ease |
| migration to future versions of Python that introduce incompatible changes to |
| the language. It allows use of the new features on a per-module basis before |
| the release in which the feature becomes standard. |
| |
| .. productionlist:: * |
n | future_statement: "from" "__future__" "import" feature ["as" name] ("," feature ["as" name])\* |
n | future_statement: "from" "__future__" "import" feature ["as" name] |
| : ("," feature ["as" name])* |
| : \| "from" "__future__" "import" "(" feature ["as" name] ("," feature ["as" name])\* [","] ")" |
| : | "from" "__future__" "import" "(" feature ["as" name] |
| : ("," feature ["as" name])* [","] ")" |
| feature: identifier |
| name: identifier |
| |
| A future statement must appear near the top of the module. The only lines that |
| can appear before a future statement are: |
| |
| * the module docstring (if any), |
n | |
| * comments, |
n | |
| * blank lines, and |
n | |
| * other future statements. |
| |
n | The features recognized by Python 2.3 are ``generators``, ``division`` and |
n | The features recognized by Python 2.6 are ``unicode_literals``, |
| ``nested_scopes``. ``generators`` and ``nested_scopes`` are redundant in 2.3 |
| ``print_function``, ``absolute_import``, ``division``, ``generators``, |
| because they are always enabled. |
| ``nested_scopes`` and ``with_statement``. ``generators``, ``with_statement``, |
| ``nested_scopes`` are redundant in Python version 2.6 and above because they are |
| always enabled. |
| |
| A future statement is recognized and treated specially at compile time: Changes |
| to the semantics of core constructs are often implemented by generating |
| different code. It may even be the case that a new feature introduces new |
| incompatible syntax (such as a new reserved word), in which case the compiler |
| may need to parse the module differently. Such decisions cannot be pushed off |
| until runtime. |
| |
| .. _exec: |
| |
| The :keyword:`exec` statement |
| ============================= |
| |
| .. index:: statement: exec |
| |
| .. productionlist:: |
n | exec_stmt: "exec" `expression` ["in" `expression` ["," `expression`]] |
n | exec_stmt: "exec" `or_expr` ["in" `expression` ["," `expression`]] |
| |
| This statement supports dynamic execution of Python code. The first expression |
| should evaluate to either a string, an open file object, or a code object. If |
| it is a string, the string is parsed as a suite of Python statements which is |
n | then executed (unless a syntax error occurs). If it is an open file, the file |
n | then executed (unless a syntax error occurs). [#]_ If it is an open file, the file |
| is parsed until EOF and executed. If it is a code object, it is simply |
| executed. In all cases, the code that's executed is expected to be valid as |
n | file input (see section :ref:`file-input`, "File input"). Be aware that the |
n | file input (see section :ref:`file-input`). Be aware that the |
| :keyword:`return` and :keyword:`yield` statements may not be used outside of |
| function definitions even within the context of code passed to the |
| :keyword:`exec` statement. |
| |
| In all cases, if the optional parts are omitted, the code is executed in the |
| current scope. If only the first expression after :keyword:`in` is specified, |
| it should be a dictionary, which will be used for both the global and the local |
| variables. If two expressions are given, they are used for the global and local |
| variables, respectively. If provided, *locals* can be any mapping object. |
| |
| .. versionchanged:: 2.4 |
n | formerly *locals* was required to be a dictionary. |
n | Formerly, *locals* was required to be a dictionary. |
| |
| .. index:: |
| single: __builtins__ |
| module: __builtin__ |
| |
| As a side effect, an implementation may insert additional keys into the |
| dictionaries given besides those corresponding to variable names set by the |
| executed code. For example, the current implementation may add a reference to |