diff options
Diffstat (limited to 'Doc/tutorial')
| -rw-r--r-- | Doc/tutorial/classes.rst | 12 | ||||
| -rw-r--r-- | Doc/tutorial/controlflow.rst | 40 | ||||
| -rw-r--r-- | Doc/tutorial/datastructures.rst | 36 | ||||
| -rw-r--r-- | Doc/tutorial/errors.rst | 2 | ||||
| -rw-r--r-- | Doc/tutorial/inputoutput.rst | 113 | ||||
| -rw-r--r-- | Doc/tutorial/interpreter.rst | 14 | ||||
| -rw-r--r-- | Doc/tutorial/introduction.rst | 619 | ||||
| -rw-r--r-- | Doc/tutorial/modules.rst | 165 | ||||
| -rw-r--r-- | Doc/tutorial/stdlib.rst | 10 | ||||
| -rw-r--r-- | Doc/tutorial/stdlib2.rst | 70 |
10 files changed, 516 insertions, 565 deletions
diff --git a/Doc/tutorial/classes.rst b/Doc/tutorial/classes.rst index cff2710..08072a3 100644 --- a/Doc/tutorial/classes.rst +++ b/Doc/tutorial/classes.rst @@ -168,7 +168,6 @@ binding:: def do_global(): global spam spam = "global spam" - spam = "test spam" do_local() print("After local assignment:", spam) @@ -184,7 +183,6 @@ The output of the example code is: .. code-block:: none - After local assignment: test spam After nonlocal assignment: nonlocal spam After global assignment: nonlocal spam @@ -654,7 +652,7 @@ will do nicely:: A piece of Python code that expects a particular abstract data type can often be passed a class that emulates the methods of that data type instead. For instance, if you have a function that formats some data from a file object, you -can define a class with methods :meth:`read` and :meth:`readline` that get the +can define a class with methods :meth:`read` and :meth:`!readline` that get the data from a string buffer instead, and pass it as an argument. .. (Unfortunately, this technique has its limitations: a class can't define @@ -698,9 +696,9 @@ example, the following code will print B, C, D in that order:: class D(C): pass - for c in [B, C, D]: + for cls in [B, C, D]: try: - raise c() + raise cls() except D: print("D") except C: @@ -740,8 +738,8 @@ pervades and unifies Python. Behind the scenes, the :keyword:`for` statement calls :func:`iter` on the container object. The function returns an iterator object that defines the method :meth:`~iterator.__next__` which accesses elements in the container one at a time. When there are no more elements, -:meth:`__next__` raises a :exc:`StopIteration` exception which tells the -:keyword:`for` loop to terminate. You can call the :meth:`__next__` method +:meth:`~iterator.__next__` raises a :exc:`StopIteration` exception which tells the +:keyword:`for` loop to terminate. You can call the :meth:`~iterator.__next__` method using the :func:`next` built-in function; this example shows how it all works:: >>> s = 'abc' diff --git a/Doc/tutorial/controlflow.rst b/Doc/tutorial/controlflow.rst index 055f547..97aea4f 100644 --- a/Doc/tutorial/controlflow.rst +++ b/Doc/tutorial/controlflow.rst @@ -19,14 +19,14 @@ example:: >>> x = int(input("Please enter an integer: ")) Please enter an integer: 42 >>> if x < 0: - ... x = 0 - ... print('Negative changed to zero') + ... x = 0 + ... print('Negative changed to zero') ... elif x == 0: - ... print('Zero') + ... print('Zero') ... elif x == 1: - ... print('Single') + ... print('Single') ... else: - ... print('More') + ... print('More') ... More @@ -370,7 +370,7 @@ defined to allow. For example:: return False retries = retries - 1 if retries < 0: - raise IOError('refusenik user') + raise IOError('uncooperative user') print(complaint) This function can be called in several ways: @@ -583,17 +583,16 @@ In the same fashion, dictionaries can deliver keyword arguments with the ``**``\ .. _tut-lambda: -Lambda Forms ------------- +Lambda Expressions +------------------ -By popular demand, a few features commonly found in functional programming -languages like Lisp have been added to Python. With the :keyword:`lambda` -keyword, small anonymous functions can be created. Here's a function that -returns the sum of its two arguments: ``lambda a, b: a+b``. Lambda forms can be -used wherever function objects are required. They are syntactically restricted -to a single expression. Semantically, they are just syntactic sugar for a -normal function definition. Like nested function definitions, lambda forms can -reference variables from the containing scope:: +Small anonymous functions can be created with the :keyword:`lambda` keyword. +This function returns the sum of its two arguments: ``lambda a, b: a+b``. +Lambda functions can be used wherever function objects are required. They are +syntactically restricted to a single expression. Semantically, they are just +syntactic sugar for a normal function definition. Like nested function +definitions, lambda functions can reference variables from the containing +scope:: >>> def make_incrementor(n): ... return lambda x: x + n @@ -604,6 +603,14 @@ reference variables from the containing scope:: >>> f(1) 43 +The above example uses a lambda expression to return a function. Another use +is to pass a small function as an argument:: + + >>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] + >>> pairs.sort(key=lambda pair: pair[1]) + >>> pairs + [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] + .. _tut-docstrings: @@ -749,4 +756,3 @@ extracted for you: .. [#] Actually, *call by object reference* would be a better description, since if a mutable object is passed, the caller will see any changes the callee makes to it (items inserted into a list). - diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst index 0ee4dca..24d2d2e 100644 --- a/Doc/tutorial/datastructures.rst +++ b/Doc/tutorial/datastructures.rst @@ -19,13 +19,13 @@ objects: .. method:: list.append(x) :noindex: - Add an item to the end of the list; equivalent to ``a[len(a):] = [x]``. + Add an item to the end of the list. Equivalent to ``a[len(a):] = [x]``. .. method:: list.extend(L) :noindex: - Extend the list by appending all the items in the given list; equivalent to + Extend the list by appending all the items in the given list. Equivalent to ``a[len(a):] = L``. @@ -40,8 +40,8 @@ objects: .. method:: list.remove(x) :noindex: - Remove the first item from the list whose value is *x*. It is an error if there - is no such item. + Remove the first item from the list whose value is *x*. It is an error if + there is no such item. .. method:: list.pop([i]) @@ -54,6 +54,12 @@ objects: will see this notation frequently in the Python Library Reference.) +.. method:: list.clear() + :noindex: + + Remove all items from the list. Equivalent to ``del a[:]``. + + .. method:: list.index(x) :noindex: @@ -70,13 +76,20 @@ objects: .. method:: list.sort() :noindex: - Sort the items of the list, in place. + Sort the items of the list in place. .. method:: list.reverse() :noindex: - Reverse the elements of the list, in place. + Reverse the elements of the list in place. + + +.. method:: list.copy() + :noindex: + + Return a shallow copy of the list. Equivalent to ``a[:]``. + An example that uses most of the list methods:: @@ -99,6 +112,10 @@ An example that uses most of the list methods:: >>> a [-1, 1, 66.25, 333, 333, 1234.5] +You might have noticed that methods like ``insert``, ``remove`` or ``sort`` that +modify the list have no return value printed -- they return ``None``. [1]_ This +is a design principle for all mutable data structures in Python. + .. _tut-lists-as-stacks: @@ -480,7 +497,7 @@ using a non-existent key. Performing ``list(d.keys())`` on a dictionary returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just use -``sorted(d.keys())`` instead). [1]_ To check whether a single key is in the +``sorted(d.keys())`` instead). [2]_ To check whether a single key is in the dictionary, use the :keyword:`in` keyword. Here is a small example using a dictionary:: @@ -677,6 +694,9 @@ interpreter will raise a :exc:`TypeError` exception. .. rubric:: Footnotes -.. [1] Calling ``d.keys()`` will return a :dfn:`dictionary view` object. It +.. [1] Other languages may return the mutated object, which allows method + chaining, such as ``d->insert("a")->remove("b")->sort();``. + +.. [2] Calling ``d.keys()`` will return a :dfn:`dictionary view` object. It supports operations like membership test and iteration, but its contents are not independent of the original dictionary -- it is only a *view*. diff --git a/Doc/tutorial/errors.rst b/Doc/tutorial/errors.rst index 2b76c32..4282151 100644 --- a/Doc/tutorial/errors.rst +++ b/Doc/tutorial/errors.rst @@ -45,7 +45,7 @@ programs, however, and result in error messages as shown here:: >>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1, in ? - ZeroDivisionError: int division or modulo by zero + ZeroDivisionError: division by zero >>> 4 + spam*3 Traceback (most recent call last): File "<stdin>", line 1, in ? diff --git a/Doc/tutorial/inputoutput.rst b/Doc/tutorial/inputoutput.rst index c804e25..b3bf0ef 100644 --- a/Doc/tutorial/inputoutput.rst +++ b/Doc/tutorial/inputoutput.rst @@ -213,10 +213,6 @@ operation. For example:: >>> print('The value of PI is approximately %5.3f.' % math.pi) The value of PI is approximately 3.142. -Since :meth:`str.format` is quite new, a lot of Python code still uses the ``%`` -operator. However, because this old style of formatting will eventually be -removed from the language, :meth:`str.format` should generally be used. - More information can be found in the :ref:`old-string-formatting` section. @@ -300,18 +296,8 @@ containing only a single newline. :: >>> f.readline() '' -``f.readlines()`` returns a list containing all the lines of data in the file. -If given an optional parameter *sizehint*, it reads that many bytes from the -file and enough more to complete a line, and returns the lines from that. This -is often used to allow efficient reading of a large file by lines, but without -having to load the entire file in memory. Only complete lines will be returned. -:: - - >>> f.readlines() - ['This is the first line of the file.\n', 'Second line of the file\n'] - -An alternative approach to reading lines is to loop over the file object. This is -memory efficient, fast, and leads to simpler code:: +For reading lines from a file, you can loop over the file object. This is memory +efficient, fast, and leads to simple code:: >>> for line in f: ... print(line, end='') @@ -319,9 +305,8 @@ memory efficient, fast, and leads to simpler code:: This is the first line of the file. Second line of the file -The alternative approach is simpler but does not provide as fine-grained -control. Since the two approaches manage line buffering differently, they -should not be mixed. +If you want to read all the lines of a file in a list you can also use +``list(f)`` or ``f.readlines()``. ``f.write(string)`` writes the contents of *string* to the file, returning the number of characters written. :: @@ -337,9 +322,11 @@ first:: >>> f.write(s) 18 -``f.tell()`` returns an integer giving the file object's current position in the -file, measured in bytes from the beginning of the file. To change the file -object's position, use ``f.seek(offset, from_what)``. The position is computed +``f.tell()`` returns an integer giving the file object's current position in the file +represented as number of bytes from the beginning of the file when in `binary mode` and +an opaque number when in `text mode`. + +To change the file object's position, use ``f.seek(offset, from_what)``. The position is computed from adding *offset* to a reference point; the reference point is selected by the *from_what* argument. A *from_what* value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as @@ -360,7 +347,10 @@ beginning of the file as the reference point. :: In text files (those opened without a ``b`` in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking -to the very file end with ``seek(0, 2)``). +to the very file end with ``seek(0, 2)``) and the only valid *offset* values are +those returned from the ``f.tell()``, or zero. Any other *offset* value produces +undefined behaviour. + When you're done with a file, call ``f.close()`` to close it and free up any system resources taken up by the open file. After calling ``f.close()``, @@ -387,47 +377,64 @@ File objects have some additional methods, such as :meth:`~file.isatty` and Reference for a complete guide to file objects. -.. _tut-pickle: +.. _tut-json: -The :mod:`pickle` Module ------------------------- +Saving structured data with :mod:`json` +--------------------------------------- -.. index:: module: pickle +.. index:: module: json -Strings can easily be written to and read from a file. Numbers take a bit more +Strings can easily be written to and read from a file. Numbers take a bit more effort, since the :meth:`read` method only returns strings, which will have to be passed to a function like :func:`int`, which takes a string like ``'123'`` -and returns its numeric value 123. However, when you want to save more complex -data types like lists, dictionaries, or class instances, things get a lot more -complicated. - -Rather than have users be constantly writing and debugging code to save -complicated data types, Python provides a standard module called :mod:`pickle`. -This is an amazing module that can take almost any Python object (even some -forms of Python code!), and convert it to a string representation; this process -is called :dfn:`pickling`. Reconstructing the object from the string -representation is called :dfn:`unpickling`. Between pickling and unpickling, -the string representing the object may have been stored in a file or data, or +and returns its numeric value 123. When you want to save more complex data +types like nested lists and dictionaries, parsing and serializing by hand +becomes complicated. + +Rather than having users constantly writing and debugging code to save +complicated data types to files, Python allows you to use the popular data +interchange format called `JSON (JavaScript Object Notation) +<http://json.org>`_. The standard module called :mod:`json` can take Python +data hierarchies, and convert them to string representations; this process is +called :dfn:`serializing`. Reconstructing the data from the string representation +is called :dfn:`deserializing`. Between serializing and deserializing, the +string representing the object may have been stored in a file or data, or sent over a network connection to some distant machine. -If you have an object ``x``, and a file object ``f`` that's been opened for -writing, the simplest way to pickle the object takes only one line of code:: +.. note:: + The JSON format is commonly used by modern applications to allow for data + exchange. Many programmers are already familiar with it, which makes + it a good choice for interoperability. + +If you have an object ``x``, you can view its JSON string representation with a +simple line of code:: + + >>> json.dumps([1, 'simple', 'list']) + '[1, "simple", "list"]' + +Another variant of the :func:`~json.dumps` function, called :func:`~json.dump`, +simply serializes the object to a :term:`text file`. So if ``f`` is a +:term:`text file` object opened for writing, we can do this:: + + json.dump(x, f) - pickle.dump(x, f) +To decode the object again, if ``f`` is a :term:`text file` object which has +been opened for reading:: -To unpickle the object again, if ``f`` is a file object which has been opened -for reading:: + x = json.load(f) - x = pickle.load(f) +This simple serialization technique can handle lists and dictionaries, but +serializing arbitrary class instances in JSON requires a bit of extra effort. +The reference for the :mod:`json` module contains an explanation of this. -(There are other variants of this, used when pickling many objects or when you -don't want to write the pickled data to a file; consult the complete -documentation for :mod:`pickle` in the Python Library Reference.) +.. seealso:: -:mod:`pickle` is the standard way to make Python objects which can be stored and -reused by other programs or by a future invocation of the same program; the -technical term for this is a :dfn:`persistent` object. Because :mod:`pickle` is -so widely used, many authors who write Python extensions take care to ensure -that new data types such as matrices can be properly pickled and unpickled. + :mod:`pickle` - the pickle module + Contrary to :ref:`JSON <tut-json>`, *pickle* is a protocol which allows + the serialization of arbitrarily complex Python objects. As such, it is + specific to Python and cannot be used to communicate with applications + written in other languages. It is also insecure by default: + deserializing pickle data coming from an untrusted source can execute + arbitrary code, if the data was crafted by a skilled attacker. diff --git a/Doc/tutorial/interpreter.rst b/Doc/tutorial/interpreter.rst index d61dafc..cdc2bf2 100644 --- a/Doc/tutorial/interpreter.rst +++ b/Doc/tutorial/interpreter.rst @@ -10,13 +10,13 @@ Using the Python Interpreter Invoking the Interpreter ======================== -The Python interpreter is usually installed as :file:`/usr/local/bin/python3.2` +The Python interpreter is usually installed as :file:`/usr/local/bin/python3.3` on those machines where it is available; putting :file:`/usr/local/bin` in your Unix shell's search path makes it possible to start it by typing the command: .. code-block:: text - python3.2 + python3.3 to the shell. [#]_ Since the choice of the directory where the interpreter lives is an installation option, other places are possible; check with your local @@ -24,11 +24,11 @@ Python guru or system administrator. (E.g., :file:`/usr/local/python` is a popular alternative location.) On Windows machines, the Python installation is usually placed in -:file:`C:\\Python32`, though you can change this when you're running the +:file:`C:\\Python33`, though you can change this when you're running the installer. To add this directory to your path, you can type the following command into the command prompt in a DOS box:: - set path=%path%;C:\python32 + set path=%path%;C:\python33 Typing an end-of-file character (:kbd:`Control-D` on Unix, :kbd:`Control-Z` on Windows) at the primary prompt causes the interpreter to exit with a zero exit @@ -95,8 +95,8 @@ with the *secondary prompt*, by default three dots (``...``). The interpreter prints a welcome message stating its version number and a copyright notice before printing the first prompt:: - $ python3.2 - Python 3.2.3 (default, May 3 2012, 15:54:42) + $ python3.3 + Python 3.3 (default, Sep 24 2012, 09:25:04) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> @@ -149,7 +149,7 @@ Executable Python Scripts On BSD'ish Unix systems, Python scripts can be made directly executable, like shell scripts, by putting the line :: - #! /usr/bin/env python3.2 + #! /usr/bin/env python3.3 (assuming that the interpreter is on the user's :envvar:`PATH`) at the beginning of the script and giving the file an executable mode. The ``#!`` must be the diff --git a/Doc/tutorial/introduction.rst b/Doc/tutorial/introduction.rst index b6d94ac..9efd1ac 100644 --- a/Doc/tutorial/introduction.rst +++ b/Doc/tutorial/introduction.rst @@ -5,7 +5,7 @@ An Informal Introduction to Python ********************************** In the following examples, input and output are distinguished by the presence or -absence of prompts (``>>>`` and ``...``): to repeat the example, you must type +absence of prompts (:term:`>>>` and :term:`...`): to repeat the example, you must type everything after the prompt, when the prompt appears; lines that do not begin with a prompt are output from the interpreter. Note that a secondary prompt on a line by itself in an example means you must type a blank line; this is used to @@ -22,9 +22,9 @@ be omitted when typing in examples. Some examples:: # this is the first comment - SPAM = 1 # and this is the second comment - # ... and now a third! - STRING = "# This is not a comment." + spam = 1 # and this is the second comment + # ... and now a third! + text = "# This is not a comment because it's inside quotes." .. _tut-calculator: @@ -44,55 +44,53 @@ Numbers The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators ``+``, ``-``, ``*`` and ``/`` work just like in most other languages -(for example, Pascal or C); parentheses can be used for grouping. For example:: +(for example, Pascal or C); parentheses (``()``) can be used for grouping. +For example:: - >>> 2+2 + >>> 2 + 2 4 - >>> # This is a comment - ... 2+2 - 4 - >>> 2+2 # and a comment on the same line as code - 4 - >>> (50-5*6)/4 + >>> 50 - 5*6 + 20 + >>> (50 - 5*6) / 4 5.0 - >>> 8/5 # Fractions aren't lost when dividing integers + >>> 8 / 5 # division always returns a floating point number 1.6 -Note: You might not see exactly the same result; floating point results can -differ from one machine to another. We will say more later about controlling -the appearance of floating point output. See also :ref:`tut-fp-issues` for a -full discussion of some of the subtleties of floating point numbers and their -representations. +The integer numbers (e.g. ``2``, ``4``, ``20``) have type :class:`int`, +the ones with a fractional part (e.g. ``5.0``, ``1.6``) have type +:class:`float`. We will see more about numeric types later in the tutorial. -To do integer division and get an integer result, -discarding any fractional result, there is another operator, ``//``:: +Division (``/``) always returns a float. To do :term:`floor division` and +get an integer result (discarding any fractional result) you can use the ``//`` +operator; to calculate the remainder you can use ``%``:: - >>> # Integer division returns the floor: - ... 7//3 + >>> 17 / 3 # classic division returns a float + 5.666666666666667 + >>> + >>> 17 // 3 # floor division discards the fractional part + 5 + >>> 17 % 3 # the % operator returns the remainder of the division 2 - >>> 7//-3 - -3 + >>> 5 * 3 + 2 # result * divisor + remainder + 17 -The equal sign (``'='``) is used to assign a value to a variable. Afterwards, no +With Python, it is possible to use the ``**`` operator to calculate powers [#]_:: + + >>> 5 ** 2 # 5 squared + 25 + >>> 2 ** 7 # 2 to the power of 7 + 128 + +The equal sign (``=``) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:: >>> width = 20 - >>> height = 5*9 + >>> height = 5 * 9 >>> width * height 900 -A value can be assigned to several variables simultaneously:: - - >>> x = y = z = 0 # Zero x, y and z - >>> x - 0 - >>> y - 0 - >>> z - 0 - -Variables must be "defined" (assigned a value) before they can be used, or an -error will occur:: +If a variable is not "defined" (assigned a value), trying to use it will +give you an error:: >>> n # try to access an undefined variable Traceback (most recent call last): @@ -107,49 +105,6 @@ convert the integer operand to floating point:: >>> 7.0 / 2 3.5 -Complex numbers are also supported; imaginary numbers are written with a suffix -of ``j`` or ``J``. Complex numbers with a nonzero real component are written as -``(real+imagj)``, or can be created with the ``complex(real, imag)`` function. -:: - - >>> 1j * 1J - (-1+0j) - >>> 1j * complex(0, 1) - (-1+0j) - >>> 3+1j*3 - (3+3j) - >>> (3+1j)*3 - (9+3j) - >>> (1+2j)/(1+1j) - (1.5+0.5j) - -Complex numbers are always represented as two floating point numbers, the real -and imaginary part. To extract these parts from a complex number *z*, use -``z.real`` and ``z.imag``. :: - - >>> a=1.5+0.5j - >>> a.real - 1.5 - >>> a.imag - 0.5 - -The conversion functions to floating point and integer (:func:`float`, -:func:`int`) don't work for complex numbers --- there is not one correct way to -convert a complex number to a real number. Use ``abs(z)`` to get its magnitude -(as a float) or ``z.real`` to get its real part:: - - >>> a=3.0+4.0j - >>> float(a) - Traceback (most recent call last): - File "<stdin>", line 1, in ? - TypeError: can't convert complex to float; use abs(z) - >>> a.real - 3.0 - >>> a.imag - 4.0 - >>> abs(a) # sqrt(a.real**2 + a.imag**2) - 5.0 - In interactive mode, the last printed expression is assigned to the variable ``_``. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:: @@ -167,20 +122,28 @@ This variable should be treated as read-only by the user. Don't explicitly assign a value to it --- you would create an independent local variable with the same name masking the built-in variable with its magic behavior. +In addition to :class:`int` and :class:`float`, Python supports other types of +numbers, such as :class:`~decimal.Decimal` and :class:`~fractions.Fraction`. +Python also has built-in support for :ref:`complex numbers <typesnumeric>`, +and uses the ``j`` or ``J`` suffix to indicate the imaginary part +(e.g. ``3+5j``). + .. _tut-strings: Strings ------- -Besides numbers, Python can also manipulate strings, which can be expressed in -several ways. They can be enclosed in single quotes or double quotes:: +Besides numbers, Python can also manipulate strings, which can be expressed +in several ways. They can be enclosed in single quotes (``'...'``) or +double quotes (``"..."``) with the same result [#]_. ``\`` can be used +to escape quotes:: - >>> 'spam eggs' + >>> 'spam eggs' # single quotes 'spam eggs' - >>> 'doesn\'t' + >>> 'doesn\'t' # use \' to escape the single quote... "doesn't" - >>> "doesn't" + >>> "doesn't" # ...or use double quotes instead "doesn't" >>> '"Yes," he said.' '"Yes," he said.' @@ -189,38 +152,40 @@ several ways. They can be enclosed in single quotes or double quotes:: >>> '"Isn\'t," she said.' '"Isn\'t," she said.' -The interpreter prints the result of string operations in the same way as they -are typed for input: inside quotes, and with quotes and other funny characters -escaped by backslashes, to show the precise value. The string is enclosed in -double quotes if the string contains a single quote and no double quotes, else -it's enclosed in single quotes. The :func:`print` function produces a more -readable output for such input strings. +In the interactive interpreter, the output string is enclosed in quotes and +special characters are escaped with backslashes. While this might sometimes +look different from the input (the enclosing quotes could change), the two +strings are equivalent. The string is enclosed in double quotes if +the string contains a single quote and no double quotes, otherwise it is +enclosed in single quotes. The :func:`print` function produces a more +readable output, by omitting the enclosing quotes and by printing escaped +and special characters:: -String literals can span multiple lines in several ways. Continuation lines can -be used, with a backslash as the last character on the line indicating that the -next line is a logical continuation of the line:: - - hello = "This is a rather long string containing\n\ - several lines of text just as you would do in C.\n\ - Note that whitespace at the beginning of the line is\ - significant." - - print(hello) - -Note that newlines still need to be embedded in the string using ``\n`` -- the -newline following the trailing backslash is discarded. This example would print -the following: - -.. code-block:: text - - This is a rather long string containing - several lines of text just as you would do in C. - Note that whitespace at the beginning of the line is significant. - -Or, strings can be surrounded in a pair of matching triple-quotes: ``"""`` or -``'''``. End of lines do not need to be escaped when using triple-quotes, but -they will be included in the string. So the following uses one escape to -avoid an unwanted initial blank line. :: + >>> '"Isn\'t," she said.' + '"Isn\'t," she said.' + >>> print('"Isn\'t," she said.') + "Isn't," she said. + >>> s = 'First line.\nSecond line.' # \n means newline + >>> s # without print(), \n is included in the output + 'First line.\nSecond line.' + >>> print(s) # with print(), \n produces a new line + First line. + Second line. + +If you don't want characters prefaced by ``\`` to be interpreted as +special characters, you can use *raw strings* by adding an ``r`` before +the first quote:: + + >>> print('C:\some\name') # here \n means newline! + C:\some + ame + >>> print(r'C:\some\name') # note the r before the quote + C:\some\name + +String literals can span multiple lines. One way is using triple-quotes: +``"""..."""`` or ``'''...'''``. End of lines are automatically +included in the string, but it's possible to prevent this by adding a ``\`` at +the end of the line. The following example:: print("""\ Usage: thingy [OPTIONS] @@ -228,7 +193,7 @@ avoid an unwanted initial blank line. :: -H hostname Hostname to connect to """) -produces the following output: +produces the following output (note that the initial newline is not included): .. code-block:: text @@ -236,143 +201,100 @@ produces the following output: -h Display this usage message -H hostname Hostname to connect to -If we make the string literal a "raw" string, ``\n`` sequences are not converted -to newlines, but the backslash at the end of the line, and the newline character -in the source, are both included in the string as data. Thus, the example:: - - hello = r"This is a rather long string containing\n\ - several lines of text much as you would do in C." - - print(hello) - -would print: - -.. code-block:: text - - This is a rather long string containing\n\ - several lines of text much as you would do in C. - Strings can be concatenated (glued together) with the ``+`` operator, and repeated with ``*``:: - >>> word = 'Help' + 'A' - >>> word - 'HelpA' - >>> '<' + word*5 + '>' - '<HelpAHelpAHelpAHelpAHelpA>' - -Two string literals next to each other are automatically concatenated; the first -line above could also have been written ``word = 'Help' 'A'``; this only works -with two literals, not with arbitrary string expressions:: - - >>> 'str' 'ing' # <- This is ok - 'string' - >>> 'str'.strip() + 'ing' # <- This is ok - 'string' - >>> 'str'.strip() 'ing' # <- This is invalid - File "<stdin>", line 1, in ? - 'str'.strip() 'ing' - ^ - SyntaxError: invalid syntax + >>> # 3 times 'un', followed by 'ium' + >>> 3 * 'un' + 'ium' + 'unununium' -Strings can be subscripted (indexed); like in C, the first character of a string -has subscript (index) 0. There is no separate character type; a character is -simply a string of size one. As in the Icon programming language, substrings -can be specified with the *slice notation*: two indices separated by a colon. -:: +Two or more *string literals* (i.e. the ones enclosed between quotes) next +to each other are automatically concatenated. :: - >>> word[4] - 'A' - >>> word[0:2] - 'He' - >>> word[2:4] - 'lp' + >>> 'Py' 'thon' + 'Python' -Slice indices have useful defaults; an omitted first index defaults to zero, an -omitted second index defaults to the size of the string being sliced. :: +This only works with two literals though, not with variables or expressions:: - >>> word[:2] # The first two characters - 'He' - >>> word[2:] # Everything except the first two characters - 'lpA' + >>> prefix = 'Py' + >>> prefix 'thon' # can't concatenate a variable and a string literal + ... + SyntaxError: invalid syntax + >>> ('un' * 3) 'ium' + ... + SyntaxError: invalid syntax -Unlike a C string, Python strings cannot be changed. Assigning to an indexed -position in the string results in an error:: +If you want to concatenate variables or a variable and a literal, use ``+``:: - >>> word[0] = 'x' - Traceback (most recent call last): - File "<stdin>", line 1, in ? - TypeError: 'str' object does not support item assignment - >>> word[:1] = 'Splat' - Traceback (most recent call last): - File "<stdin>", line 1, in ? - TypeError: 'str' object does not support slice assignment + >>> prefix + 'thon' + 'Python' -However, creating a new string with the combined content is easy and efficient:: +This feature is particularly useful when you want to break long strings:: - >>> 'x' + word[1:] - 'xelpA' - >>> 'Splat' + word[4] - 'SplatA' + >>> text = ('Put several strings within parentheses ' + 'to have them joined together.') + >>> text + 'Put several strings within parentheses to have them joined together.' -Here's a useful invariant of slice operations: ``s[:i] + s[i:]`` equals ``s``. -:: +Strings can be *indexed* (subscripted), with the first character having index 0. +There is no separate character type; a character is simply a string of size +one:: - >>> word[:2] + word[2:] - 'HelpA' - >>> word[:3] + word[3:] - 'HelpA' + >>> word = 'Python' + >>> word[0] # character in position 0 + 'P' + >>> word[5] # character in position 5 + 'n' -Degenerate slice indices are handled gracefully: an index that is too large is -replaced by the string size, an upper bound smaller than the lower bound returns -an empty string. :: +Indices may also be negative numbers, to start counting from the right:: - >>> word[1:100] - 'elpA' - >>> word[10:] - '' - >>> word[2:1] - '' + >>> word[-1] # last character + 'n' + >>> word[-2] # second-last character + 'o' + >>> word[-6] + 'P' -Indices may be negative numbers, to start counting from the right. For example:: +Note that since -0 is the same as 0, negative indices start from -1. - >>> word[-1] # The last character - 'A' - >>> word[-2] # The last-but-one character - 'p' - >>> word[-2:] # The last two characters - 'pA' - >>> word[:-2] # Everything except the last two characters - 'Hel' +In addition to indexing, *slicing* is also supported. While indexing is used +to obtain individual characters, *slicing* allows you to obtain substring:: -But note that -0 is really the same as 0, so it does not count from the right! -:: + >>> word[0:2] # characters from position 0 (included) to 2 (excluded) + 'Py' + >>> word[2:5] # characters from position 2 (included) to 5 (excluded) + 'tho' - >>> word[-0] # (since -0 equals 0) - 'H' +Note how the start is always included, and the end always excluded. This +makes sure that ``s[:i] + s[i:]`` is always equal to ``s``:: -Out-of-range negative slice indices are truncated, but don't try this for -single-element (non-slice) indices:: + >>> word[:2] + word[2:] + 'Python' + >>> word[:4] + word[4:] + 'Python' - >>> word[-100:] - 'HelpA' - >>> word[-10] # error - Traceback (most recent call last): - File "<stdin>", line 1, in ? - IndexError: string index out of range +Slice indices have useful defaults; an omitted first index defaults to zero, an +omitted second index defaults to the size of the string being sliced. :: + + >>> word[:2] # character from the beginning to position 2 (excluded) + 'Py' + >>> word[4:] # characters from position 4 (included) to the end + 'on' + >>> word[-2:] # characters from the second-last (included) to the end + 'on' One way to remember how slices work is to think of the indices as pointing *between* characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of *n* characters has index *n*, for example:: - +---+---+---+---+---+ - | H | e | l | p | A | - +---+---+---+---+---+ - 0 1 2 3 4 5 - -5 -4 -3 -2 -1 + +---+---+---+---+---+---+ + | P | y | t | h | o | n | + +---+---+---+---+---+---+ + 0 1 2 3 4 5 6 + -6 -5 -4 -3 -2 -1 -The first row of numbers gives the position of the indices 0...5 in the string; +The first row of numbers gives the position of the indices 0...6 in the string; the second row gives the corresponding negative indices. The slice from *i* to *j* consists of all characters between the edges labeled *i* and *j*, respectively. @@ -381,6 +303,38 @@ For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of ``word[1:3]`` is 2. +Attempting to use a index that is too large will result in an error:: + + >>> word[42] # the word only has 7 characters + Traceback (most recent call last): + File "<stdin>", line 1, in <module> + IndexError: string index out of range + +However, out of range slice indexes are handled gracefully when used for +slicing:: + + >>> word[4:42] + 'on' + >>> word[42:] + '' + +Python strings cannot be changed --- they are :term:`immutable`. +Therefore, assigning to an indexed position in the string results in an error:: + + >>> word[0] = 'J' + ... + TypeError: 'str' object does not support item assignment + >>> word[2:] = 'py' + ... + TypeError: 'str' object does not support item assignment + +If you need a different string, you should create a new one:: + + >>> 'J' + word[1:] + 'Jython' + >>> word[:2] + 'py' + 'Pypy' + The built-in function :func:`len` returns the length of a string:: >>> s = 'supercalifragilisticexpialidocious' @@ -390,7 +344,7 @@ The built-in function :func:`len` returns the length of a string:: .. seealso:: - :ref:`typesseq` + :ref:`textseq` Strings are examples of *sequence types*, and support the common operations supported by such types. @@ -407,149 +361,96 @@ The built-in function :func:`len` returns the length of a string:: the left operand of the ``%`` operator are described in more detail here. -.. _tut-unicodestrings: - -About Unicode -------------- - -.. sectionauthor:: Marc-André Lemburg <mal@lemburg.com> - - -Starting with Python 3.0 all strings support Unicode (see -http://www.unicode.org/). - -Unicode has the advantage of providing one ordinal for every character in every -script used in modern and ancient texts. Previously, there were only 256 -possible ordinals for script characters. Texts were typically bound to a code -page which mapped the ordinals to script characters. This lead to very much -confusion especially with respect to internationalization (usually written as -``i18n`` --- ``'i'`` + 18 characters + ``'n'``) of software. Unicode solves -these problems by defining one code page for all scripts. - -If you want to include special characters in a string, -you can do so by using the Python *Unicode-Escape* encoding. The following -example shows how:: +.. _tut-lists: - >>> 'Hello\u0020World !' - 'Hello World !' +Lists +----- -The escape sequence ``\u0020`` indicates to insert the Unicode character with -the ordinal value 0x0020 (the space character) at the given position. +Python knows a number of *compound* data types, used to group together other +values. The most versatile is the *list*, which can be written as a list of +comma-separated values (items) between square brackets. Lists might contain +items of different types, but usually the items all have the same type. :: -Other characters are interpreted by using their respective ordinal values -directly as Unicode ordinals. If you have literal strings in the standard -Latin-1 encoding that is used in many Western countries, you will find it -convenient that the lower 256 characters of Unicode are the same as the 256 -characters of Latin-1. + >>> squares = [1, 4, 9, 16, 25] + >>> squares + [1, 4, 9, 16, 25] -Apart from these standard encodings, Python provides a whole set of other ways -of creating Unicode strings on the basis of a known encoding. +Like strings (and all other built-in :term:`sequence` type), lists can be +indexed and sliced:: -To convert a string into a sequence of bytes using a specific encoding, -string objects provide an :func:`encode` method that takes one argument, the -name of the encoding. Lowercase names for encodings are preferred. :: + >>> squares[0] # indexing returns the item + 1 + >>> squares[-1] + 25 + >>> squares[-3:] # slicing returns a new list + [9, 16, 25] - >>> "Äpfel".encode('utf-8') - b'\xc3\x84pfel' +All slice operations return a new list containing the requested elements. This +means that the following slice returns a new (shallow) copy of the list:: -.. _tut-lists: + >>> squares[:] + [1, 4, 9, 16, 25] -Lists ------ +Lists also supports operations like concatenation:: -Python knows a number of *compound* data types, used to group together other -values. The most versatile is the *list*, which can be written as a list of -comma-separated values (items) between square brackets. List items need not all -have the same type. :: - - >>> a = ['spam', 'eggs', 100, 1234] - >>> a - ['spam', 'eggs', 100, 1234] - -Like string indices, list indices start at 0, and lists can be sliced, -concatenated and so on:: - - >>> a[0] - 'spam' - >>> a[3] - 1234 - >>> a[-2] - 100 - >>> a[1:-1] - ['eggs', 100] - >>> a[:2] + ['bacon', 2*2] - ['spam', 'eggs', 'bacon', 4] - >>> 3*a[:3] + ['Boo!'] - ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!'] + >>> squares + [36, 49, 64, 81, 100] + [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] -All slice operations return a new list containing the requested elements. This -means that the following slice returns a shallow copy of the list *a*:: +Unlike strings, which are :term:`immutable`, lists are a :term:`mutable` +type, i.e. it is possible to change their content:: - >>> a[:] - ['spam', 'eggs', 100, 1234] + >>> cubes = [1, 8, 27, 65, 125] # something's wrong here + >>> 4 ** 3 # the cube of 4 is 64, not 65! + 64 + >>> cubes[3] = 64 # replace the wrong value + >>> cubes + [1, 8, 27, 64, 125] -Unlike strings, which are *immutable*, it is possible to change individual -elements of a list:: +You can also add new items at the end of the list, by using +the :meth:`~list.append` *method* (we will see more about methods later):: - >>> a - ['spam', 'eggs', 100, 1234] - >>> a[2] = a[2] + 23 - >>> a - ['spam', 'eggs', 123, 1234] + >>> cubes.append(216) # add the cube of 6 + >>> cubes.append(7 ** 3) # and the cube of 7 + >>> cubes + [1, 8, 27, 64, 125, 216, 343] Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:: - >>> # Replace some items: - ... a[0:2] = [1, 12] - >>> a - [1, 12, 123, 1234] - >>> # Remove some: - ... a[0:2] = [] - >>> a - [123, 1234] - >>> # Insert some: - ... a[1:1] = ['bletch', 'xyzzy'] - >>> a - [123, 'bletch', 'xyzzy', 1234] - >>> # Insert (a copy of) itself at the beginning - >>> a[:0] = a - >>> a - [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234] - >>> # Clear the list: replace all items with an empty list - >>> a[:] = [] - >>> a + >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] + >>> letters + ['a', 'b', 'c', 'd', 'e', 'f', 'g'] + >>> # replace some values + >>> letters[2:5] = ['C', 'D', 'E'] + >>> letters + ['a', 'b', 'C', 'D', 'E', 'f', 'g'] + >>> # now remove them + >>> letters[2:5] = [] + >>> letters + ['a', 'b', 'f', 'g'] + >>> # clear the list by replacing all the elements with an empty list + >>> letters[:] = [] + >>> letters [] The built-in function :func:`len` also applies to lists:: - >>> a = ['a', 'b', 'c', 'd'] - >>> len(a) + >>> letters = ['a', 'b', 'c', 'd'] + >>> len(letters) 4 It is possible to nest lists (create lists containing other lists), for example:: - >>> q = [2, 3] - >>> p = [1, q, 4] - >>> len(p) - 3 - >>> p[1] - [2, 3] - >>> p[1][0] - 2 - -You can add something to the end of the list:: - - >>> p[1].append('xtra') - >>> p - [1, [2, 3, 'xtra'], 4] - >>> q - [2, 3, 'xtra'] - -Note that in the last example, ``p[1]`` and ``q`` really refer to the same -object! We'll come back to *object semantics* later. - + >>> a = ['a', 'b', 'c'] + >>> n = [1, 2, 3] + >>> x = [a, n] + >>> x + [['a', 'b', 'c'], [1, 2, 3]] + >>> x[0] + ['a', 'b', 'c'] + >>> x[0][1] + 'b' .. _tut-firststeps: @@ -600,19 +501,19 @@ This example introduces several new features. guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount. -* The :func:`print` function writes the value of the expression(s) it is - given. It differs from just writing the expression you want to write (as we did - earlier in the calculator examples) in the way it handles multiple - expressions, floating point quantities, - and strings. Strings are printed without quotes, and a space is inserted - between items, so you can format things nicely, like this:: +* The :func:`print` function writes the value of the argument(s) it is given. + It differs from just writing the expression you want to write (as we did + earlier in the calculator examples) in the way it handles multiple arguments, + floating point quantities, and strings. Strings are printed without quotes, + and a space is inserted between items, so you can format things nicely, like + this:: >>> i = 256*256 >>> print('The value of i is', i) The value of i is 65536 - The keyword *end* can be used to avoid the newline after the output, or end - the output with a different string:: + The keyword argument *end* can be used to avoid the newline after the output, + or end the output with a different string:: >>> a, b = 0, 1 >>> while b < 1000: @@ -620,3 +521,15 @@ This example introduces several new features. ... a, b = b, a+b ... 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987, + + +.. rubric:: Footnotes + +.. [#] Since ``**`` has higher precedence than ``-``, ``-3**2`` will be + interpreted as ``-(3**2)`` and thus result in ``-9``. To avoid this + and get ``9``, you can use ``(-3)**2``. + +.. [#] Unlike other languages, special characters such as ``\n`` have the + same meaning with both single (``'...'``) and double (``"..."``) quotes. + The only difference between the two is that within single quotes you don't + need to escape ``"`` (but you have to escape ``\'``) and vice versa. diff --git a/Doc/tutorial/modules.rst b/Doc/tutorial/modules.rst index 86c1a0d..1902964 100644 --- a/Doc/tutorial/modules.rst +++ b/Doc/tutorial/modules.rst @@ -72,7 +72,8 @@ More on Modules A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only -the *first* time the module is imported somewhere. [#]_ +the *first* time the module name is encountered in an import statement. [#]_ +(They are also run if the file is executed as a script.) Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can @@ -182,57 +183,45 @@ directory. This is an error unless the replacement is intended. See section "Compiled" Python files ----------------------- -As an important speed-up of the start-up time for short programs that use a lot -of standard modules, if a file called :file:`spam.pyc` exists in the directory -where :file:`spam.py` is found, this is assumed to contain an -already-"byte-compiled" version of the module :mod:`spam`. The modification time -of the version of :file:`spam.py` used to create :file:`spam.pyc` is recorded in -:file:`spam.pyc`, and the :file:`.pyc` file is ignored if these don't match. - -Normally, you don't need to do anything to create the :file:`spam.pyc` file. -Whenever :file:`spam.py` is successfully compiled, an attempt is made to write -the compiled version to :file:`spam.pyc`. It is not an error if this attempt -fails; if for any reason the file is not written completely, the resulting -:file:`spam.pyc` file will be recognized as invalid and thus ignored later. The -contents of the :file:`spam.pyc` file are platform independent, so a Python -module directory can be shared by machines of different architectures. +To speed up loading modules, Python caches the compiled version of each module +in the ``__pycache__`` directory under the name :file:`module.{version}.pyc`, +where the version encodes the format of the compiled file; it generally contains +the Python version number. For example, in CPython release 3.3 the compiled +version of spam.py would be cached as ``__pycache__/spam.cpython-33.pyc``. This +naming convention allows compiled modules from different releases and different +versions of Python to coexist. + +Python checks the modification date of the source against the compiled version +to see if it's out of date and needs to be recompiled. This is a completely +automatic process. Also, the compiled modules are platform-independent, so the +same library can be shared among systems with different architectures. + +Python does not check the cache in two circumstances. First, it always +recompiles and does not store the result for the module that's loaded directly +from the command line. Second, it does not check the cache if there is no +source module. To support a non-source (compiled only) distribution, the +compiled module must be in the source directory, and there must not be a source +module. Some tips for experts: -* When the Python interpreter is invoked with the :option:`-O` flag, optimized - code is generated and stored in :file:`.pyo` files. The optimizer currently - doesn't help much; it only removes :keyword:`assert` statements. When - :option:`-O` is used, *all* :term:`bytecode` is optimized; ``.pyc`` files are - ignored and ``.py`` files are compiled to optimized bytecode. +* You can use the :option:`-O` or :option:`-OO` switches on the Python command + to reduce the size of a compiled module. The ``-O`` switch removes assert + statements, the ``-OO`` switch removes both assert statements and __doc__ + strings. Since some programs may rely on having these available, you should + only use this option if you know what you're doing. "Optimized" modules have + a .pyo rather than a .pyc suffix and are usually smaller. Future releases may + change the effects of optimization. -* Passing two :option:`-O` flags to the Python interpreter (:option:`-OO`) will - cause the bytecode compiler to perform optimizations that could in some rare - cases result in malfunctioning programs. Currently only ``__doc__`` strings are - removed from the bytecode, resulting in more compact :file:`.pyo` files. Since - some programs may rely on having these available, you should only use this - option if you know what you're doing. +* A program doesn't run any faster when it is read from a ``.pyc`` or ``.pyo`` + file than when it is read from a ``.py`` file; the only thing that's faster + about ``.pyc`` or ``.pyo`` files is the speed with which they are loaded. -* A program doesn't run any faster when it is read from a :file:`.pyc` or - :file:`.pyo` file than when it is read from a :file:`.py` file; the only thing - that's faster about :file:`.pyc` or :file:`.pyo` files is the speed with which - they are loaded. +* The module :mod:`compileall` can create .pyc files (or .pyo files when + :option:`-O` is used) for all modules in a directory. -* When a script is run by giving its name on the command line, the bytecode for - the script is never written to a :file:`.pyc` or :file:`.pyo` file. Thus, the - startup time of a script may be reduced by moving most of its code to a module - and having a small bootstrap script that imports that module. It is also - possible to name a :file:`.pyc` or :file:`.pyo` file directly on the command - line. - -* It is possible to have a file called :file:`spam.pyc` (or :file:`spam.pyo` - when :option:`-O` is used) without a file :file:`spam.py` for the same module. - This can be used to distribute a library of Python code in a form that is - moderately hard to reverse engineer. - - .. index:: module: compileall - -* The module :mod:`compileall` can create :file:`.pyc` files (or :file:`.pyo` - files when :option:`-O` is used) for all modules in a directory. +* There is more detail on this process, including a flow chart of the + decisions, in PEP 3147. .. _tut-standardmodules: @@ -289,21 +278,24 @@ defines. It returns a sorted list of strings:: >>> dir(fibo) ['__name__', 'fib', 'fib2'] >>> dir(sys) # doctest: +NORMALIZE_WHITESPACE - ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', - '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', - '_current_frames', '_getframe', '_mercurial', '_xoptions', 'abiflags', - 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', - 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info', + ['__displayhook__', '__doc__', '__egginsert', '__excepthook__', + '__loader__', '__name__', '__package__', '__plen', '__stderr__', + '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', + '_debugmallocstats', '_getframe', '_home', '_mercurial', '_xoptions', + 'abiflags', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', + 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', + 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', - 'gettotalrefcount', 'gettrace', 'hash_info', 'hexversion', 'int_info', - 'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', - 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', - 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', - 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', - 'version', 'version_info', 'warnoptions'] + 'gettotalrefcount', 'gettrace', 'hash_info', 'hexversion', + 'implementation', 'int_info', 'intern', 'maxsize', 'maxunicode', + 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', + 'platform', 'prefix', 'ps1', 'setcheckinterval', 'setdlopenflags', + 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', + 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', + 'warnoptions'] Without arguments, :func:`dir` lists the names you have defined currently:: @@ -324,29 +316,34 @@ want a list of those, they are defined in the standard module >>> import builtins >>> dir(builtins) # doctest: +NORMALIZE_WHITESPACE ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', - 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', - 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', + 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', + 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', + 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', + 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', + 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', - 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', - 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', - 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', - 'PendingDeprecationWarning', 'ReferenceError', 'ResourceWarning', - 'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError', - 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', - 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', - 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', - 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', - 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', - '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'ascii', - 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', - 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', - 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', - 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', - 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', - 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', - 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', - 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', - 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip'] + 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', + 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', + 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', + 'NotImplementedError', 'OSError', 'OverflowError', + 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', + 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', + 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', + 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', + 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', + 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', + 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__', + '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', + 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', + 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', + 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', + 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', + 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', + 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', + 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', + 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', + 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', + 'zip'] .. _tut-packages: @@ -370,7 +367,9 @@ There are also many different operations you might want to perform on sound data (such as mixing, adding echo, applying an equalizer function, creating an artificial stereo effect), so in addition you will be writing a never-ending stream of modules to perform these operations. Here's a possible structure for -your package (expressed in terms of a hierarchical filesystem):: +your package (expressed in terms of a hierarchical filesystem): + +.. code-block:: text sound/ Top-level package __init__.py Initialize the sound package @@ -467,7 +466,7 @@ list of module names that should be imported when ``from package import *`` is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don't see a use for importing \* from their package. For -example, the file :file:`sounds/effects/__init__.py` could contain the following +example, the file :file:`sound/effects/__init__.py` could contain the following code:: __all__ = ["echo", "surround", "reverse"] @@ -542,6 +541,6 @@ modules found in a package. .. rubric:: Footnotes .. [#] In fact function definitions are also 'statements' that are 'executed'; the - execution of a module-level function enters the function name in the module's - global symbol table. + execution of a module-level function definition enters the function name in + the module's global symbol table. diff --git a/Doc/tutorial/stdlib.rst b/Doc/tutorial/stdlib.rst index 128e6a6..7e7a154 100644 --- a/Doc/tutorial/stdlib.rst +++ b/Doc/tutorial/stdlib.rst @@ -15,7 +15,7 @@ operating system:: >>> import os >>> os.getcwd() # Return the current working directory - 'C:\\Python31' + 'C:\\Python33' >>> os.chdir('/server/accesslogs') # Change current working directory >>> os.system('mkdir today') # Run the command mkdir in the system shell 0 @@ -203,7 +203,7 @@ Data Compression ================ Common data archiving and compression formats are directly supported by modules -including: :mod:`zlib`, :mod:`gzip`, :mod:`bz2`, :mod:`zipfile` and +including: :mod:`zlib`, :mod:`gzip`, :mod:`bz2`, :mod:`lzma`, :mod:`zipfile` and :mod:`tarfile`. :: >>> import zlib @@ -281,8 +281,10 @@ file:: def test_average(self): self.assertEqual(average([20, 30, 70]), 40.0) self.assertEqual(round(average([1, 5, 7]), 1), 4.3) - self.assertRaises(ZeroDivisionError, average, []) - self.assertRaises(TypeError, average, 20, 30, 70) + with self.assertRaises(ZeroDivisionError): + average([]) + with self.assertRaises(TypeError): + average(20, 30, 70) unittest.main() # Calling from the command line invokes all tests diff --git a/Doc/tutorial/stdlib2.rst b/Doc/tutorial/stdlib2.rst index 2265cd0..c1dd69a 100644 --- a/Doc/tutorial/stdlib2.rst +++ b/Doc/tutorial/stdlib2.rst @@ -71,9 +71,9 @@ formatting numbers with group separators:: Templating ========== -The :mod:`string` module includes a versatile :class:`Template` class with a -simplified syntax suitable for editing by end-users. This allows users to -customize their applications without having to alter the application. +The :mod:`string` module includes a versatile :class:`~string.Template` class +with a simplified syntax suitable for editing by end-users. This allows users +to customize their applications without having to alter the application. The format uses placeholder names formed by ``$`` with valid Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with @@ -85,11 +85,11 @@ spaces. Writing ``$$`` creates a single escaped ``$``:: >>> t.substitute(village='Nottingham', cause='the ditch fund') 'Nottinghamfolk send $10 to the ditch fund.' -The :meth:`substitute` method raises a :exc:`KeyError` when a placeholder is not -supplied in a dictionary or a keyword argument. For mail-merge style -applications, user supplied data may be incomplete and the -:meth:`safe_substitute` method may be more appropriate --- it will leave -placeholders unchanged if data is missing:: +The :meth:`~string.Template.substitute` method raises a :exc:`KeyError` when a +placeholder is not supplied in a dictionary or a keyword argument. For +mail-merge style applications, user supplied data may be incomplete and the +:meth:`~string.Template.safe_substitute` method may be more appropriate --- +it will leave placeholders unchanged if data is missing:: >>> t = Template('Return the $item to $owner.') >>> d = dict(item='unladen swallow') @@ -132,8 +132,9 @@ templates for XML files, plain text reports, and HTML web reports. Working with Binary Data Record Layouts ======================================= -The :mod:`struct` module provides :func:`pack` and :func:`unpack` functions for -working with variable length binary record formats. The following example shows +The :mod:`struct` module provides :func:`~struct.pack` and +:func:`~struct.unpack` functions for working with variable length binary +record formats. The following example shows how to loop through header information in a ZIP file without using the :mod:`zipfile` module. Pack codes ``"H"`` and ``"I"`` represent two and four byte unsigned numbers respectively. The ``"<"`` indicates that they are @@ -141,7 +142,9 @@ standard size and in little-endian byte order:: import struct - data = open('myfile.zip', 'rb').read() + with open('myfile.zip', 'rb') as f: + data = f.read() + start = 0 for i in range(3): # show the first 3 file headers start += 14 @@ -199,7 +202,7 @@ While those tools are powerful, minor design errors can result in problems that are difficult to reproduce. So, the preferred approach to task coordination is to concentrate all access to a resource in a single thread and then use the :mod:`queue` module to feed that thread with requests from other threads. -Applications using :class:`Queue` objects for inter-thread communication and +Applications using :class:`~queue.Queue` objects for inter-thread communication and coordination are easier to design, more readable, and more reliable. @@ -229,8 +232,9 @@ This produces the following output: By default, informational and debugging messages are suppressed and the output is sent to standard error. Other output options include routing messages through email, datagrams, sockets, or to an HTTP Server. New filters can select -different routing based on message priority: :const:`DEBUG`, :const:`INFO`, -:const:`WARNING`, :const:`ERROR`, and :const:`CRITICAL`. +different routing based on message priority: :const:`~logging.DEBUG`, +:const:`~logging.INFO`, :const:`~logging.WARNING`, :const:`~logging.ERROR`, +and :const:`~logging.CRITICAL`. The logging system can be configured directly from Python or can be loaded from a user editable configuration file for customized logging without altering the @@ -273,7 +277,7 @@ applications include caching objects that are expensive to create:: Traceback (most recent call last): File "<stdin>", line 1, in <module> d['primary'] # entry was automatically removed - File "C:/python31/lib/weakref.py", line 46, in __getitem__ + File "C:/python33/lib/weakref.py", line 46, in __getitem__ o = self.data[key]() KeyError: 'primary' @@ -287,11 +291,11 @@ Many data structure needs can be met with the built-in list type. However, sometimes there is a need for alternative implementations with different performance trade-offs. -The :mod:`array` module provides an :class:`array()` object that is like a list -that stores only homogeneous data and stores it more compactly. The following -example shows an array of numbers stored as two byte unsigned binary numbers -(typecode ``"H"``) rather than the usual 16 bytes per entry for regular lists of -Python int objects:: +The :mod:`array` module provides an :class:`~array.array()` object that is like +a list that stores only homogeneous data and stores it more compactly. The +following example shows an array of numbers stored as two byte unsigned binary +numbers (typecode ``"H"``) rather than the usual 16 bytes per entry for regular +lists of Python int objects:: >>> from array import array >>> a = array('H', [4000, 10, 700, 22222]) @@ -300,10 +304,10 @@ Python int objects:: >>> a[1:3] array('H', [10, 700]) -The :mod:`collections` module provides a :class:`deque()` object that is like a -list with faster appends and pops from the left side but slower lookups in the -middle. These objects are well suited for implementing queues and breadth first -tree searches:: +The :mod:`collections` module provides a :class:`~collections.deque()` object +that is like a list with faster appends and pops from the left side but slower +lookups in the middle. These objects are well suited for implementing queues +and breadth first tree searches:: >>> from collections import deque >>> d = deque(["task1", "task2", "task3"]) @@ -349,8 +353,8 @@ not want to run a full list sort:: Decimal Floating Point Arithmetic ================================= -The :mod:`decimal` module offers a :class:`Decimal` datatype for decimal -floating point arithmetic. Compared to the built-in :class:`float` +The :mod:`decimal` module offers a :class:`~decimal.Decimal` datatype for +decimal floating point arithmetic. Compared to the built-in :class:`float` implementation of binary floating point, the class is especially helpful for * financial applications and other uses which require exact decimal @@ -371,13 +375,15 @@ becomes significant if the results are rounded to the nearest cent:: >>> round(.70 * 1.05, 2) 0.73 -The :class:`Decimal` result keeps a trailing zero, automatically inferring four -place significance from multiplicands with two place significance. Decimal -reproduces mathematics as done by hand and avoids issues that can arise when -binary floating point cannot exactly represent decimal quantities. +The :class:`~decimal.Decimal` result keeps a trailing zero, automatically +inferring four place significance from multiplicands with two place +significance. Decimal reproduces mathematics as done by hand and avoids +issues that can arise when binary floating point cannot exactly represent +decimal quantities. -Exact representation enables the :class:`Decimal` class to perform modulo -calculations and equality tests that are unsuitable for binary floating point:: +Exact representation enables the :class:`~decimal.Decimal` class to perform +modulo calculations and equality tests that are unsuitable for binary floating +point:: >>> Decimal('1.00') % Decimal('.10') Decimal('0.00') |
