This is /home/pdm/install/Python-2.1/Doc/lib/python-lib.info, produced by makeinfo version 4.0 from lib.texi. April 15, 2001 2.1  File: python-lib.info, Node: Classes and functions 2, Next: TestCase Objects, Prev: Re-using old test code, Up: unittest Classes and functions --------------------- `TestCase()' Instances of the `TestCase' class represent the smallest testable units in a set of tests. This class is intended to be used as a base class, with specific tests being implemented by concrete subclasses. This class implements the interface needed by the test runner to allow it to drive the test, and methods that the test code can use to check for and report various kinds of failures. `FunctionTestCase(testFunc[, setUp[, tearDown[, description]]])' This class implements the portion of the `TestCase' interface which allows the test runner to drive the test, but does not provide the methods which test code can use to check and report errors. This is used to create test cases using legacy test code, allowing it to be integrated into a `unittest'-based test framework. `TestSuite([tests])' This class represents an aggregation of individual tests cases and test suites. The class presents the interface needed by the test runner to allow it to be run as any other test case, but all the contained tests and test suites are executed. Additional methods are provided to add test cases and suites to the aggregation. If TESTS is given, it must be a sequence of individual tests that will be added to the suite. `TestLoader()' This class is responsible for loading tests according to various criteria and returning them wrapped in a `TestSuite'. It can load all tests within a given module or `TestCase' class. When loading from a module, it considers all `TestCase'-derived classes. For each such class, it creates an instance for each method with a name beginning with the string `test'. `defaultTestLoader' Instance of the `TestLoader' class which can be shared. If no customization of the `TestLoader' is needed, this instance can always be used instead of creating new instances. `TextTestRunner([stream[, descriptions[, verbosity]]])' A basic test runner implementation which prints results on standard output. It has a few configurable parameters, but is essentially very simple. Graphical applications which run test suites should provide alternate implementations. `main([module[, defaultTest[, argv[, testRunner[, testRunner]]]]])' A command-line program that runs a set of tests; this is primarily for making test modules conveniently executable. The simplest use for this function is: if __name__ == '__main__': unittest.main()  File: python-lib.info, Node: TestCase Objects, Next: TestSuite Objects, Prev: Classes and functions 2, Up: unittest TestCase Objects ---------------- Each `TestCase' instance represents a single test, but each concrete subclass may be used to define multiple tests -- the concrete class represents a single test fixture. The fixture is created and cleaned up for each test case. `TestCase' instances provide three groups of methods: one group used to run the test, another used by the test implementation to check conditions and report failures, and some inquiry methods allowing information about the test itself to be gathered. Methods in the first group are: `setUp()' Method called to prepare the test fixture. This is called immediately before calling the test method; any exception raised by this method will be considered an error rather than a test failure. The default implementation does nothing. `tearDown()' Method called immediately after the test method has been called and the result recorded. This is called even if the test method raised an exception, so the implementation in subclasses may need to be particularly careful about checking internal state. Any exception raised by this method will be considered an error rather than a test failure. This method will only be called if the `setUp()' succeeds, regardless of the outcome of the test method. The default implementation does nothing. `run([result])' Run the test, collecting the result into the test result object passed as RESULT. If RESULT is omitted or `None', a temporary result object is created and used, but is not made available to the caller. This is equivalent to simply calling the `TestCase' instance. `debug()' Run the test without collecting the result. This allows exceptions raised by the test to be propogated to the caller, and can be used to support running tests under a debugger. The test code can use any of the following methods to check for and report failures. `assert_(expr[, msg])' `failUnless(expr[, msg])' Signal a test failure if EXPR is false; the explanation for the error will be MSG if given, otherwise it will be `None'. `assertEqual(first, second[, msg])' `failUnlessEqual(first, second[, msg])' Test that FIRST and SECOND are equal. If the values do not compare equal, the test will fail with the explanation given by MSG, or `None'. Note that using `failUnlessEqual()' improves upon doing the comparison as the first parameter to `failUnless()': the default value for MSG can be computed to include representations of both FIRST and SECOND. `assertNotEqual(first, second[, msg])' `failIfEqual(first, second[, msg])' Test that FIRST and SECOND are not equal. If the values do compare equal, the test will fail with the explanation given by MSG, or `None'. Note that using `failIfEqual()' improves upon doing the comparison as the first parameter to `failUnless()' is that the default value for MSG can be computed to include representations of both FIRST and SECOND. `assertRaises(exception, callable, ...)' `failUnlessRaises(exception, callable, ...)' Test that an exception is raised when CALLABLE is called with any positional or keyword arguments that are also passed to `assertRaises()'. The test passes if EXCEPTION is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as EXCEPTION. `failIf(expr[, msg])' The inverse of the `failUnless()' method is the `failIf()' method. This signals a test failure if EXPR is true, with MSG or `None' for the error message. `fail([msg])' Signals a test failure unconditionally, with MSG or `None' for the error message. `failureException' This class attribute gives the exception raised by the `test()' method. If a test framework needs to use a specialized exception, possibly to carry additional information, it must subclass this exception in order to "play fair" with the framework. The initial value of this attribute is `AssertionError'. Testing frameworks can use the following methods to collect information on the test: `countTestCases()' Return the number of tests represented by the this test object. For `TestCase' instances, this will always be `1', but this method is also implemented by the `TestSuite' class, which can return larger values. `defaultTestResult()' Return the default type of test result object to be used to run this test. `id()' Return a string identifying the specific test case. This is usually the full name of the test method, including the module and class names. `shortDescription()' Returns a one-line description of the test, or `None' if no description has been provided. The default implementation of this method returns the first line of the test method's docstring, if available, or `None'.  File: python-lib.info, Node: TestSuite Objects, Next: TestResult Objects, Prev: TestCase Objects, Up: unittest TestSuite Objects ----------------- `TestSuite' objects behave much like `TestCase' objects, except they do not actually implement a test. Instead, they are used to aggregate tests into groups that should be run together. Some additional methods are available to add tests to `TestSuite' instances: `addTest(test)' Add a `TestCase' or `TestSuite' to the set of tests that make up the suite. `addTests(tests)' Add all the tests from a sequence of `TestCase' and `TestSuite' instances to this test suite.  File: python-lib.info, Node: TestResult Objects, Next: TestLoader Objects, Prev: TestSuite Objects, Up: unittest TestResult Objects ------------------ A `TestResult' object stores the results of a set of tests. The `TestCase' and `TestSuite' classes ensure that results are properly stored; test authors do not need to worry about recording the outcome of tests. Testing frameworks built on top of `unittest' may want access to the `TestResult' object generated by running a set of tests for reporting purposes; a `TestResult' instance is returned by the `TestRunner.run()' method for this purpose. Each instance holds the total number of tests run, and collections of failures and errors that occurred among those test runs. The collections contain tuples of `(TESTCASE, EXCEPTIONINFO)', where EXCEPTIONINFO is a tuple as returned by `sys.exc_info()'. `TestResult' instances have the following attributes that will be of interest when inspecting the results of running a set of tests: `errors' A list containing pairs of `TestCase' instances and the `sys.exc_info()' results for tests which raised an exception but did not signal a test failure. `failures' A list containing pairs of `TestCase' instances and the `sys.exc_info()' results for tests which signalled a failure in the code under test. `testsRun' The number of tests which have been started. `wasSuccessful()' Returns true if all tests run so far have passed, otherwise returns false. The following methods of the `TestResult' class are used to maintain the internal data structures, and mmay be extended in subclasses to support additional reporting requirements. This is particularly useful in building GUI tools which support interactive reporting while tests are being run. `startTest(test)' Called when the test case TEST is about to be run. `stopTest(test)' Called when the test case TEST has been executed, regardless of the outcome. `addError(test, err)' Called when the test case TEST raises an exception without signalling a test failure. ERR is a tuple of the form returned by `sys.exc_info()': `(TYPE, VALUE, TRACEBACK)'. `addFailure(test, err)' Called when the test case TEST signals a failure. ERR is a tuple of the form returned by `sys.exc_info()': `(TYPE, VALUE, TRACEBACK)'. `addSuccess(test)' This method is called for a test that does not fail; TEST is the test case object. One additional method is available for `TestResult' objects: `stop()' This method can be called to signal that the set of tests being run should be aborted. Once this has been called, the `TestRunner' object return to its caller without running any additional tests. This is used by the `TextTestRunner' class to stop the test framework when the user signals an interrupt from the keyboard. GUI tools which provide runners can use this in a similar manner.  File: python-lib.info, Node: TestLoader Objects, Prev: TestResult Objects, Up: unittest TestLoader Objects ------------------ The `TestLoader' class is used to create test suites from classes and modules. Normally, there is no need to create an instance of this class; the `unittest' module provides an instance that can be shared as the `defaultTestLoader' module attribute. Using a subclass or instance would allow customization of some configurable properties. `TestLoader' objects have the following methods: `loadTestsFromTestCase(testCaseClass)' Return a suite of all tests cases contained in the `TestCase'-derived class `testCaseClass'. `loadTestsFromModule(module)' Return a suite of all tests cases contained in the given module. This method searches MODULE for classes derived from `TestCase' and creates an instance of the class for each test method defined for the class. *Warning:* While using a hierarchy of `Testcase'-derived classes can be convenient in sharing fixtures and helper functions, defining test methods on base classes that are not intended to be instantiated directly does not play well with this method. Doing so, however, can be useful when the fixtures are different and defined in subclasses. `loadTestsFromName(name[, module])' Return a suite of all tests cases given a string specifier. The specifier NAME may resolve either to a module, a test case class, a test method within a test case class, or a callable object which returns a `TestCase' or `TestSuite' instance. The method optionally resolves NAME relative to a given module. `loadTestsFromNames(names[, module])' Similar to `loadTestsFromName()', but takes a sequence of names rather than a single name. The return value is a test suite which supports all the tests defined for each name. `getTestCaseNames(testCaseClass)' Return a sorted sequence of method names found within TESTCASECLASS. The following attributes of a `TestLoader' can be configured either by subclassing or assignment on an instance: `testMethodPrefix' String giving the prefix of method names which will be interpreted as test methods. The default value is `'test''. `sortTestMethodsUsing' Function to be used to compare method names when sorting them in `getTestCaseNames()'. The default value is the built-in `cmp()' function; it can be set to `None' to disable the sort. `suiteClass' Callable object that constructs a test suite from a list of tests. No methods on the resulting object are needed. The default value is the `TestSuite' class.  File: python-lib.info, Node: math, Next: cmath, Prev: unittest, Up: Miscellaneous Services Mathematical functions ====================== Mathematical functions (`sin()' etc.). This module is always available. It provides access to the mathematical functions defined by the C standard. These functions cannot be used with complex numbers; use the functions of the same name from the `cmath' module if you require support for complex numbers. The distinction between functions which support complex numbers and those which don't is made since most users do not want to learn quite as much mathematics as required to understand complex numbers. Receiving an exception instead of a complex result allows earlier detection of the unexpected complex number used as a parameter, so that the programmer can determine how and why it was generated in the first place. The following functions provided by this module: `acos(x)' Return the arc cosine of X. `asin(x)' Return the arc sine of X. `atan(x)' Return the arc tangent of X. `atan2(y, x)' Return `atan(Y / X)'. `ceil(x)' Return the ceiling of X as a float. `cos(x)' Return the cosine of X. `cosh(x)' Return the hyperbolic cosine of X. `exp(x)' Return `e**X'. `fabs(x)' Return the absolute value of the floating point number X. `floor(x)' Return the floor of X as a float. `fmod(x, y)' Return `fmod(X, Y)', as defined by the platform C library. Note that the Python expression `X % Y' may not return the same result. `frexp(x)' Return the mantissa and exponent of X as the pair `(M, E)'. M is a float and E is an integer such that `X == M * 2**E'. If X is zero, returns `(0.0, 0)', otherwise `0.5 <= abs(M) < 1'. `hypot(x, y)' Return the Euclidean distance, `sqrt(X*X + Y*Y)'. `ldexp(x, i)' Return `X * (2**I)'. `log(x)' Return the natural logarithm of X. `log10(x)' Return the base-10 logarithm of X. `modf(x)' Return the fractional and integer parts of X. Both results carry the sign of X. The integer part is returned as a float. `pow(x, y)' Return `X**Y'. `sin(x)' Return the sine of X. `sinh(x)' Return the hyperbolic sine of X. `sqrt(x)' Return the square root of X. `tan(x)' Return the tangent of X. `tanh(x)' Return the hyperbolic tangent of X. Note that `frexp()' and `modf()' have a different call/return pattern than their C equivalents: they take a single argument and return a pair of values, rather than returning their second return value through an `output parameter' (there is no such thing in Python). The module also defines two mathematical constants: `pi' The mathematical constant _pi_. `e' The mathematical constant _e_. See also: *Note cmath:: Complex number versions of many of these functions.  File: python-lib.info, Node: cmath, Next: random, Prev: math, Up: Miscellaneous Services Mathematical functions for complex numbers ========================================== Mathematical functions for complex numbers. This module is always available. It provides access to mathematical functions for complex numbers. The functions are: `acos(x)' Return the arc cosine of X. `acosh(x)' Return the hyperbolic arc cosine of X. `asin(x)' Return the arc sine of X. `asinh(x)' Return the hyperbolic arc sine of X. `atan(x)' Return the arc tangent of X. `atanh(x)' Return the hyperbolic arc tangent of X. `cos(x)' Return the cosine of X. `cosh(x)' Return the hyperbolic cosine of X. `exp(x)' Return the exponential value `e**X'. `log(x)' Return the natural logarithm of X. `log10(x)' Return the base-10 logarithm of X. `sin(x)' Return the sine of X. `sinh(x)' Return the hyperbolic sine of X. `sqrt(x)' Return the square root of X. `tan(x)' Return the tangent of X. `tanh(x)' Return the hyperbolic tangent of X. The module also defines two mathematical constants: `pi' The mathematical constant _pi_, as a real. `e' The mathematical constant _e_, as a real. Note that the selection of functions is similar, but not identical, to that in module `math'. The reason for having two modules is that some users aren't interested in complex numbers, and perhaps don't even know what they are. They would rather have `math.sqrt(-1)' raise an exception than return a complex number. Also note that the functions defined in `cmath' always return a complex number, even if the answer can be expressed as a real number (in which case the complex number has an imaginary part of zero).  File: python-lib.info, Node: random, Next: whrandom, Prev: cmath, Up: Miscellaneous Services Generate pseudo-random numbers ============================== Generate pseudo-random numbers with various common distributions. This module implements pseudo-random number generators for various distributions. For integers, uniform selection from a range. For sequences, uniform selection of a random element, and a function to generate a random permutation of a list in-place. On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma, and beta distributions. For generating distribution of angles, the circular uniform and von Mises distributions are available. Almost all module functions depend on the basic function `random()', which generates a random float uniformly in the semi-open range [0.0, 1.0). Python uses the standard Wichmann-Hill generator, combining three pure multiplicative congruential generators of modulus 30269, 30307 and 30323. Its period (how many numbers it generates before repeating the sequence exactly) is 6,953,607,871,644. While of much higher quality than the `rand()' function supplied by most C libraries, the theoretical properties are much the same as for a single linear congruential generator of large modulus. It is not suitable for all purposes, and is completely unsuitable for cryptographic purposes. The functions in this module are not threadsafe: if you want to call these functions from multiple threads, you should explicitly serialize the calls. Else, because no critical sections are implemented internally, calls from different threads may see the same return values. The functions supplied by this module are actually bound methods of a hidden instance of the `random.Random' class. You can instantiate your own instances of `Random' to get generators that don't share state. This is especially useful for multi-threaded programs, creating a different instance of `Random' for each thread, and using the `jumpahead()' method to ensure that the generated sequences seen by each thread don't overlap (see example below). Class `Random' can also be subclassed if you want to use a different basic generator of your own devising: in that case, override the `random()', `seed()', `getstate()', `setstate()' and `jumpahead()' methods. Here's one way to create threadsafe distinct and non-overlapping generators: def create_generators(num, delta, firstseed=None): """Return list of num distinct generators. Each generator has its own unique segment of delta elements from Random.random()'s full period. Seed the first generator with optional arg firstseed (default is None, to seed from current time). """ from random import Random g = Random(firstseed) result = [g] for i in range(num - 1): laststate = g.getstate() g = Random() g.setstate(laststate) g.jumpahead(delta) result.append(g) return result gens = create_generators(10, 1000000) That creates 10 distinct generators, which can be passed out to 10 distinct threads. The generators don't share state so can be called safely in parallel. So long as no thread calls its `g.random()' more than a million times (the second argument to `create_generators()', the sequences seen by each thread will not overlap. The period of the underlying Wichmann-Hill generator limits how far this technique can be pushed. Just for fun, note that since we know the period, `jumpahead()' can also be used to "move backward in time:" >>> g = Random(42) # arbitrary >>> g.random() 0.25420336316883324 >>> g.jumpahead(6953607871644L - 1) # move *back* one >>> g.random() 0.25420336316883324 Bookkeeping functions: `seed([x])' Initialize the basic random number generator. Optional argument X can be any hashable object. If NONE, current system time is used; current system time is also used to initialize the generator when the module is first imported. If NONE or an int or long, `hash(X)' is used instead. If X is an int or long, X is used directly. Distinct values between 0 and 27814431486575L inclusive are guaranteed to yield distinct internal states (this guarantee is specific to the default Wichmann-Hill generator, and may not apply to subclasses supplying their own basic generator). `whseed([x])' This is obsolete, supplied for bit-level compatibility with versions of Python prior to 2.1. See `seed' for details. `whseed' does not guarantee that distinct integer arguments yield distinct internal states, and can yield no more than about 2**24 distinct internal states in all. `getstate()' Return an object capturing the current internal state of the generator. This object can be passed to `setstate()' to restore the state. _Added in Python version 2.1_ `setstate(state)' STATE should have been obtained from a previous call to `getstate()', and `setstate()' restores the internal state of the generator to what it was at the time `setstate()' was called. _Added in Python version 2.1_ `jumpahead(n)' Change the internal state to what it would be if `random()' were called N times, but do so quickly. N is a non-negative integer. This is most useful in multi-threaded programs, in conjuction with multiple instances of the RANDOM class: `setstate()' or `seed()' can be used to force all instances into the same internal state, and then `jumpahead()' can be used to force the instances' states as far apart as you like (up to the period of the generator). _Added in Python version 2.1_ Functions for integers: `randrange([start,] stop[, step])' Return a randomly selected element from `range(START, STOP, STEP)'. This is equivalent to `choice(range(START, STOP, STEP))', but doesn't actually build a range object. _Added in Python version 1.5.2_ `randint(a, b)' _This is deprecated in Python 2.0. Use `randrange()' instead._ Return a random integer N such that `A <= N <= B'. Functions for sequences: `choice(seq)' Return a random element from the non-empty sequence SEQ. `shuffle(x[, random])' Shuffle the sequence X in place. The optional argument RANDOM is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function `random()'. Note that for even rather small `len(X)', the total number of permutations of X is larger than the period of most random number generators; this implies that most permutations of a long sequence can never be generated. The following functions generate specific real-valued distributions. Function parameters are named after the corresponding variables in the distribution's equation, as used in common mathematical practice; most of these equations can be found in any statistics text. `random()' Return the next random floating point number in the range [0.0, 1.0). `uniform(a, b)' Return a random real number N such that `A <= N < B'. `betavariate(alpha, beta)' Beta distribution. Conditions on the parameters are `ALPHA > -1' and `BETA > -1'. Returned values range between 0 and 1. `cunifvariate(mean, arc)' Circular uniform distribution. MEAN is the mean angle, and ARC is the range of the distribution, centered around the mean angle. Both values must be expressed in radians, and can range between 0 and _pi_. Returned values range between `MEAN - ARC/2' and `MEAN + ARC/2'. `expovariate(lambd)' Exponential distribution. LAMBD is 1.0 divided by the desired mean. (The parameter would be called "lambda", but that is a reserved word in Python.) Returned values range from 0 to positive infinity. `gamma(alpha, beta)' Gamma distribution. (_Not_ the gamma function!) Conditions on the parameters are `ALPHA > -1' and `BETA > 0'. `gauss(mu, sigma)' Gaussian distribution. MU is the mean, and SIGMA is the standard deviation. This is slightly faster than the `normalvariate()' function defined below. `lognormvariate(mu, sigma)' Log normal distribution. If you take the natural logarithm of this distribution, you'll get a normal distribution with mean MU and standard deviation SIGMA. MU can have any value, and SIGMA must be greater than zero. `normalvariate(mu, sigma)' Normal distribution. MU is the mean, and SIGMA is the standard deviation. `vonmisesvariate(mu, kappa)' MU is the mean angle, expressed in radians between 0 and 2*_pi_, and KAPPA is the concentration parameter, which must be greater than or equal to zero. If KAPPA is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*_pi_. `paretovariate(alpha)' Pareto distribution. ALPHA is the shape parameter. `weibullvariate(alpha, beta)' Weibull distribution. ALPHA is the scale parameter and BETA is the shape parameter. See also: Wichmann, B. A. & Hill, I. D., "Algorithm AS 183: An efficient and portable pseudo-random number generator", 31 (1982) 188-190.  File: python-lib.info, Node: whrandom, Next: bisect, Prev: random, Up: Miscellaneous Services Pseudo-random number generator ============================== Floating point pseudo-random number generator. _This is deprecated in Python 2.1. Use `random' instead._ *Note:* This module was an implementation detail of the `random' module in releases of Python prior to 2.1. It is no longer used. Please do not use this module directly; use `random' instead. This module implements a Wichmann-Hill pseudo-random number generator class that is also named `whrandom'. Instances of the `whrandom' class conform to the Random Number Generator interface described in section . They also offer the following method, specific to the Wichmann-Hill algorithm: `seed([x, y, z])' Initializes the random number generator from the integers X, Y and Z. When the module is first imported, the random number is initialized using values derived from the current time. If X, Y, and Z are either omitted or `0', the seed will be computed from the current system time. If one or two of the parameters are `0', but not all three, the zero values are replaced by ones. This causes some apparently different seeds to be equal, with the corresponding result on the pseudo-random series produced by the generator. `choice(seq)' Chooses a random element from the non-empty sequence SEQ and returns it. `randint(a, b)' Returns a random integer N such that `A<=N<=B'. `random()' Returns the next random floating point number in the range [0.0 ... 1.0). `seed(x, y, z)' Initializes the random number generator from the integers X, Y and Z. When the module is first imported, the random number is initialized using values derived from the current time. `uniform(a, b)' Returns a random real number N such that `A<=N. This module provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over the more common approach. The module is called `bisect' because it uses a basic bisection algorithm to do its work. The source code may be most useful as a working example of the algorithm (i.e., the boundary conditions are already right!). The following functions are provided: `bisect_left(list, item[, lo[, hi]])' Locate the proper insertion point for ITEM in LIST to maintain sorted order. The parameters LO and HI may be used to specify a subset of the list which should be considered; by default the entire list is used. If ITEM is already present in LIST, the insertion point will be before (to the left of) any existing entries. The return value is suitable for use as the first parameter to `LIST.insert()'. This assumes that LIST is already sorted. _Added in Python version 2.1_ `bisect_right(list, item[, lo[, hi]])' Similar to `bisect_left()', but returns an insertion point which comes after (to the right of) any existing entries of ITEM in LIST. _Added in Python version 2.1_ `bisect(...)' Alias for `bisect_right()'. `insort_left(list, item[, lo[, hi]])' Insert ITEM in LIST in sorted order. This is equivalent to `LIST.insert(bisect.bisect_left(LIST, ITEM, LO, HI), ITEM)'. This assumes that LIST is already sorted. _Added in Python version 2.1_ `insort_right(list, item[, lo[, hi]])' Similar to `insort_left()', but inserting ITEM in LIST after any existing entries of ITEM. _Added in Python version 2.1_ `insort(...)' Alias for `insort_right()'. * Menu: * bisect-example::  File: python-lib.info, Node: bisect-example, Prev: bisect, Up: bisect Example ------- The `bisect()' function is generally useful for categorizing numeric data. This example uses `bisect()' to look up a letter grade for an exam total (say) based on a set of ordered numeric breakpoints: 85 and up is an `A', 75..84 is a `B', etc. >>> grades = "FEDCBA" >>> breakpoints = [30, 44, 66, 75, 85] >>> from bisect import bisect >>> def grade(total): ... return grades[bisect(breakpoints, total)] ... >>> grade(66) 'C' >>> map(grade, [33, 99, 77, 44, 12, 88]) ['E', 'A', 'B', 'D', 'F', 'A']  File: python-lib.info, Node: array, Next: ConfigParser, Prev: bisect, Up: Miscellaneous Services Efficient arrays of numeric values ================================== Efficient arrays of uniformly typed numeric values. This module defines a new object type which can efficiently represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a "type code", which is a single character. The following type codes are defined: Type code C Type Minimum size in bytes ------ ----- ----- 'c' character 1 'b' signed int 1 'B' unsigned int 1 'h' signed int 2 'H' unsigned int 2 'i' signed int 2 'I' unsigned int 2 'l' signed int 4 'L' unsigned int 4 'f' float 4 'd' double 8 The actual representation of values is determined by the machine architecture (strictly speaking, by the C implementation). The actual size can be accessed through the `itemsize' attribute. The values stored for `'L'' and `'I'' items will be represented as Python long integers when retrieved, because Python's plain integer type cannot represent the full range of C's unsigned (long) integers. The module defines the following function and type object: `array(typecode[, initializer])' Return a new array whose items are restricted by TYPECODE, and initialized from the optional INITIALIZER value, which must be a list or a string. The list or string is passed to the new array's `fromlist()' or `fromstring()' method (see below) to add initial items to the array. `ArrayType' Type object corresponding to the objects returned by `array()'. Array objects support the following data items and methods: `typecode' The typecode character used to create the array. `itemsize' The length in bytes of one array item in the internal representation. `append(x)' Append a new item with value X to the end of the array. `buffer_info()' Return a tuple `(ADDRESS, LENGTH)' giving the current memory address and the length in bytes of the buffer used to hold array's contents. This is occasionally useful when working with low-level (and inherently unsafe) I/O interfaces that require memory addresses, such as certain `ioctl()' operations. The returned numbers are valid as long as the array exists and no length-changing operations are applied to it. `byteswap()' "Byteswap" all items of the array. This is only supported for values which are 1, 2, 4, or 8 bytes in size; for other types of values, `RuntimeError' is raised. It is useful when reading data from a file written on a machine with a different byte order. `count(x)' Return the number of occurences of X in the array. `extend(a)' Append array items from A to the end of the array. `fromfile(f, n)' Read N items (as machine values) from the file object F and append them to the end of the array. If less than N items are available, `EOFError' is raised, but the items that were available are still inserted into the array. F must be a real built-in file object; something else with a `read()' method won't do. `fromlist(list)' Append items from the list. This is equivalent to `for x in LIST: a.append(x)' except that if there is a type error, the array is unchanged. `fromstring(s)' Appends items from the string, interpreting the string as an array of machine values (i.e. as if it had been read from a file using the `fromfile()' method). `index(x)' Return the smallest I such that I is the index of the first occurence of X in the array. `insert(i, x)' Insert a new item with value X in the array before position I. `pop([i])' Removes the item with the index I from the array and returns it. The optional argument defaults to `-1', so that by default the last item is removed and returned. `read(f, n)' _This is deprecated in Python 1.5.1. Use the `fromfile()' method._ Read N items (as machine values) from the file object F and append them to the end of the array. If less than N items are available, `EOFError' is raised, but the items that were available are still inserted into the array. F must be a real built-in file object; something else with a `read()' method won't do. `remove(x)' Remove the first occurence of X from the array. `reverse()' Reverse the order of the items in the array. `tofile(f)' Write all items (as machine values) to the file object F. `tolist()' Convert the array to an ordinary list with the same items. `tostring()' Convert the array to an array of machine values and return the string representation (the same sequence of bytes that would be written to a file by the `tofile()' method.) `write(f)' _This is deprecated in Python 1.5.1. Use the `tofile()' method._ Write all items (as machine values) to the file object F. When an array object is printed or converted to a string, it is represented as `array(TYPECODE, INITIALIZER)'. The INITIALIZER is omitted if the array is empty, otherwise it is a string if the TYPECODE is `'c'', otherwise it is a list of numbers. The string is guaranteed to be able to be converted back to an array with the same type and value using reverse quotes (```'), so long as the `array()' function has been imported using `from array import array'. Examples: array('l') array('c', 'hello world') array('l', [1, 2, 3, 4, 5]) array('d', [1.0, 2.0, 3.14]) See also: *Note struct:: Packing and unpacking of heterogeneous binary data. *Note xdrlib:: Packing and unpacking of External Data Representation (XDR) data as used in some remote procedure call systems. `The Numerical Python Manual'{The Numeric Python extension (NumPy) defines another array type; see for further information about Numerical Python. (A PDF version of the NumPy manual is available at .}  File: python-lib.info, Node: ConfigParser, Next: fileinput, Prev: array, Up: Miscellaneous Services Configuration file parser ========================= Configuration file parser. This module was documented by Ken Manheimer . This module was documented by Barry Warsaw . This module was documented by Eric S. Raymond . This section was written by Christopher G. Petrilli . This module defines the class `ConfigParser'. The `ConfigParser' class implements a basic configuration file parser language which provides a structure similar to what you would find on Microsoft Windows INI files. You can use this to write Python programs which can be customized by end users easily. The configuration file consists of sections, lead by a `[section]' header and followed by `name: value' entries, with continuations in the style of RFC 822; `name=value' is also accepted. Note that leading whitespace is removed from values. The optional values can contain format strings which refer to other values in the same section, or values in a special `DEFAULT' section. Additional defaults can be provided upon initialization and retrieval. Lines beginning with `#' or `;' are ignored and may be used to provide comments. For example: foodir: %(dir)s/whatever dir=frob would resolve the `%(dir)s' to the value of `dir' (`frob' in this case). All reference expansions are done on demand. Default values can be specified by passing them into the `ConfigParser' constructor as a dictionary. Additional defaults may be passed into the `get()' method which will override all others. `ConfigParser([defaults])' Return a new instance of the `ConfigParser' class. When DEFAULTS is given, it is initialized into the dictionary of intrinsic defaults. The keys must be strings, and the values must be appropriate for the `%()s' string interpolation. Note that __NAME__ is an intrinsic default; its value is the section name, and will override any value provided in DEFAULTS. `NoSectionError' Exception raised when a specified section is not found. `DuplicateSectionError' Exception raised when multiple sections with the same name are found, or if `add_section()' is called with the name of a section that is already present. `NoOptionError' Exception raised when a specified option is not found in the specified section. `InterpolationError' Exception raised when problems occur performing string interpolation. `InterpolationDepthError' Exception raised when string interpolation cannot be completed because the number of iterations exceeds `MAX_INTERPOLATION_DEPTH'. `MissingSectionHeaderError' Exception raised when attempting to parse a file which has no section headers. `ParsingError' Exception raised when errors occur attempting to parse a file. `MAX_INTERPOLATION_DEPTH' The maximum depth for recursive interpolation for `get()' when the RAW parameter is false. Setting this does not change the allowed recursion depth. See also: *Note shlex:: Support for a creating UNIX shell-like minilanguages which can be used as an alternate format for application configuration files. * Menu: * ConfigParser Objects::  File: python-lib.info, Node: ConfigParser Objects, Prev: ConfigParser, Up: ConfigParser ConfigParser Objects -------------------- `ConfigParser' instances have the following methods: `defaults()' Return a dictionary containing the instance-wide defaults. `sections()' Return a list of the sections available; `DEFAULT' is not included in the list. `add_section(section)' Add a section named SECTION to the instance. If a section by the given name already exists, `DuplicateSectionError' is raised. `has_section(section)' Indicates whether the named section is present in the configuration. The `DEFAULT' section is not acknowledged. `options(section)' Returns a list of options available in the specified SECTION. `has_option(section, option)' If the given section exists, and contains the given option. return 1; otherwise return 0. (New in 1.6) `read(filenames)' Read and parse a list of filenames. If FILENAMES is a string or Unicode string, it is treated as a single filename. `readfp(fp[, filename])' Read and parse configuration data from the file or file-like object in FP (only the `readline()' method is used). If FILENAME is omitted and FP has a `name' attribute, that is used for FILENAME; the default is `'. `get(section, option[, raw[, vars]])' Get an OPTION value for the provided SECTION. All the `%' interpolations are expanded in the return values, based on the defaults passed into the constructor, as well as the options VARS provided, unless the RAW argument is true. `getint(section, option)' A convenience method which coerces the OPTION in the specified SECTION to an integer. `getfloat(section, option)' A convenience method which coerces the OPTION in the specified SECTION to a floating point number. `getboolean(section, option)' A convenience method which coerces the OPTION in the specified SECTION to a boolean value. Note that the only accepted values for the option are `0' and `1', any others will raise `ValueError'. `set(section, option, value)' If the given section exists, set the given option to the specified value; otherwise raise `NoSectionError'. (New in 1.6) `write(fileobject)' Write a representation of the configuration to the specified file object. This representation can be parsed by a future `read()' call. (New in 1.6) `remove_option(section, option)' Remove the specified OPTION from the specified SECTION. If the section does not exist, raise `NoSectionError'. If the option existed to be removed, return 1; otherwise return 0. (New in 1.6) `remove_section(section)' Remove the specified SECTION from the configuration. If the section in fact existed, return 1. Otherwise return 0. `optionxform(option)' Transforms the option name OPTION as found in an input file or as passed in by client code to the form that should be used in the internal structures. The default implementation returns a lower-case version of OPTION; subclasses may override this or client code can set an attribute of this name on instances to affect this behavior. Setting this to `str()', for example, would make option names case sensitive.