id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
2,100 | howeverout of range slice indexes are handled gracefully when used for slicingword[ : 'onword[ :'python strings cannot be changed -they are immutable thereforeassigning to an indexed position in the string results in an errorword[ 'jtypeerror'strobject does not support item assignment word[ :'pytypeerror'strobject does not support item assignment if you need different stringyou should create new one'jword[ :'jythonword[: 'py'pypythe built-in function len(returns the length of strings 'supercalifragilisticexpialidociouslen( see alsotextseq strings are examples of sequence typesand support the common operations supported by such types string-methods strings support large number of methods for basic transformations and searching -strings string literals that have embedded expressions formatstrings information about string formatting with str format(old-string-formatting the old formatting operations invoked when strings are the left operand of the operator are described in more detail here lists python knows number of compound data typesused to group together other values the most versatile is the listwhich can be written as list of comma-separated values (itemsbetween square brackets lists might contain items of different typesbut usually the items all have the same type squares [ squares [ like strings (and all other built-in sequence type)lists can be indexed and slicedsquares[ indexing returns the item squares[- (continues on next page an informal introduction to python |
2,101 | (continued from previous page squares[- :[ slicing returns new list all slice operations return new list containing the requested elements this means that the following slice returns new (shallowcopy of the listsquares[:[ lists also support operations like concatenationsquares [ [ unlike stringswhich are immutablelists are mutable typei it is possible to change their contentcubes [ something' wrong here * the cube of is not cubes[ replace the wrong value cubes [ you can also add new items at the end of the listby using the append(method (we will see more about methods later)cubes append( add the cube of cubes append( * and the cube of cubes [ assignment to slices is also possibleand this can even change the size of the list or clear it entirelyletters [' '' '' '' '' '' '' 'letters [' '' '' '' '' '' '' 'replace some values letters[ : [' '' '' 'letters [' '' '' '' '' '' '' 'now remove them letters[ : [letters [' '' '' '' 'clear the list by replacing all the elements with an empty list letters[:[letters [the built-in function len(also applies to listsletters [' '' '' '' 'len(letters it is possible to nest lists (create lists containing other lists)for example using python as calculator |
2,102 | [' '' '' ' [ [anx [[' '' '' '][ ] [ [' '' '' ' [ ][ ' first steps towards programming of coursewe can use python for more complicated tasks than adding two and two together for instancewe can write an initial sub-sequence of the fibonacci series as followsfibonacci seriesthe sum of two elements defines the next ab while print(aab ba+ this example introduces several new features the first line contains multiple assignmentthe variables and simultaneously get the new values and on the last line this is used againdemonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place the right-hand side expressions are evaluated from the left to the right the while loop executes as long as the condition (herea remains true in pythonlike in cany non-zero integer value is truezero is false the condition may also be string or list valuein fact any sequenceanything with non-zero length is trueempty sequences are false the test used in the example is simple comparison the standard comparison operators are written the same as in (greater than)=(equal to)(greater than or equal toand !(not equal tothe body of the loop is indentedindentation is python' way of grouping statements at the interactive promptyou have to type tab or space(sfor each indented line in practice you will prepare more complicated input for python with text editorall decent text editors have an auto-indent facility when compound statement is entered interactivelyit must be followed by blank line to indicate completion (since the parser cannot guess when you have typed the last linenote that each line within basic block must be indented by the same amount the print(function writes the value of the argument(sit is given it differs from just writing the expression you want to write (as we did earlier in the calculator examplesin the way it handles multiple argumentsfloating point quantitiesand strings strings are printed without quotesand space is inserted between itemsso you can format things nicelylike this an informal introduction to python |
2,103 | * print('the value of is'ithe value of is the keyword argument end can be used to avoid the newline after the outputor end the output with different stringab while print(aend=','ab ba+ , , , , , , , , , , , , , , , , first steps towards programming |
2,104 | an informal introduction to python |
2,105 | four more control flow tools besides the while statement just introducedpython knows the usual control flow statements known from other languageswith some twists if statements perhaps the most well-known statement type is the if statement for examplex int(input("please enter an integer")please enter an integer if print('negative changed to zero'elif = print('zero'elif = print('single'elseprint('more'more there can be zero or more elif partsand the else part is optional the keyword 'elifis short for 'else if'and is useful to avoid excessive indentation an if elif elif sequence is substitute for the switch or case statements found in other languages for statements the for statement in python differs bit from what you may be used to in or pascal rather than always iterating over an arithmetic progression of numbers (like in pascal)or giving the user the ability to define both the iteration step and halting condition (as )python' for statement iterates over the items of any sequence ( list or string)in the order that they appear in the sequence for example (no pun intended)measure some stringswords ['cat''window''defenestrate'for in wordsprint(wlen( )cat window defenestrate |
2,106 | if you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items)it is recommended that you first make copy iterating over sequence does not implicitly make copy the slice notation makes this especially convenientfor in words[:]loop over slice copy of the entire list if len( words insert( wwords ['defenestrate''cat''window''defenestrate'with for in words:the example would attempt to create an infinite listinserting defenestrate over and over again the range(function if you do need to iterate over sequence of numbersthe built-in function range(comes in handy it generates arithmetic progressionsfor in range( )print( the given end point is never part of the generated sequencerange( generates valuesthe legal indices for items of sequence of length it is possible to let the range start at another numberor to specify different increment (even negativesometimes this is called the 'step')range( range( range(- - - - - - to iterate over the indices of sequenceyou can combine range(and len(as followsa ['mary''had'' ''little''lamb'for in range(len( ))print(ia[ ] mary had little lamb in most such caseshoweverit is convenient to use the enumerate(functionsee looping techniques strange thing happens if you just print range more control flow tools |
2,107 | print(range( )range( in many ways the object returned by range(behaves as if it is listbut in fact it isn' it is an object which returns the successive items of the desired sequence when you iterate over itbut it doesn' really make the listthus saving space we say such an object is iterablethat issuitable as target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted we have seen that the for statement is such an iterator the function list(is anotherit creates lists from iterableslist(range( )[ later we will see more functions that return iterables and take iterables as argument break and continue statementsand else clauses on loops the break statementlike in cbreaks out of the innermost enclosing for or while loop loop statements may have an else clauseit is executed when the loop terminates through exhaustion of the list (with foror when the condition becomes false (with while)but not when the loop is terminated by break statement this is exemplified by the following loopwhich searches for prime numbersfor in range( )for in range( )if = print( 'equals' '*' //xbreak elseloop fell through without finding factor print( 'is prime number' is prime number is prime number equals is prime number equals is prime number equals equals (yesthis is the correct code look closelythe else clause belongs to the for loopnot the if statement when used with loopthe else clause has more in common with the else clause of try statement than it does that of if statementsa try statement' else clause runs when no exception occursand loop' else clause runs when no break occurs for more on the try statement and exceptionssee handling exceptions the continue statementalso borrowed from ccontinues with the next iteration of the loopfor num in range( )if num = print("found an even number"numcontinue print("found number"numfound an even number (continues on next page break and continue statementsand else clauses on loops |
2,108 | (continued from previous pagefound number found an even number found number found an even number found number found an even number found number pass statements the pass statement does nothing it can be used when statement is required syntactically but the program requires no action for examplewhile truepass busy-wait for keyboard interrupt (ctrl+cthis is commonly used for creating minimal classesclass myemptyclasspass another place pass can be used is as place-holder for function or conditional body when you are working on new codeallowing you to keep thinking at more abstract level the pass is silently ignoreddef initlog(*args)pass remember to implement this defining functions we can create function that writes the fibonacci series to an arbitrary boundarydef fib( )write fibonacci series up to """print fibonacci series up to ""ab while nprint(aend='ab ba+ print(now call the function we just definedfib( the keyword def introduces function definition it must be followed by the function name and the parenthesized list of formal parameters the statements that form the body of the function start at the next lineand must be indented the first statement of the function body can optionally be string literalthis string literal is the function' documentation stringor docstring (more about docstrings can be found in the section documentation more control flow tools |
2,109 | strings there are tools which use docstrings to automatically produce online or printed documentationor to let the user interactively browse through codeit' good practice to include docstrings in code that you writeso make habit of it the execution of function introduces new symbol table used for the local variables of the function more preciselyall variable assignments in function store the value in the local symbol tablewhereas variable references first look in the local symbol tablethen in the local symbol tables of enclosing functionsthen in the global symbol tableand finally in the table of built-in names thusglobal variables cannot be directly assigned value within function (unless named in global statement)although they may be referenced the actual parameters (argumentsto function call are introduced in the local symbol table of the called function when it is calledthusarguments are passed using call by value (where the value is always an object referencenot the value of the object when function calls another functiona new local symbol table is created for that call function definition introduces the function name in the current symbol table the value of the function name has type that is recognized by the interpreter as user-defined function this value can be assigned to another name which can then also be used as function this serves as general renaming mechanismfib fib ( coming from other languagesyou might object that fib is not function but procedure since it doesn' return value in facteven functions without return statement do return valuealbeit rather boring one this value is called none (it' built-in namewriting the value none is normally suppressed by the interpreter if it would be the only value written you can see it if you really want to using print()fib( print(fib( )none it is simple to write function that returns list of the numbers of the fibonacci seriesinstead of printing itdef fib ( )return fibonacci series up to """return list containing the fibonacci series up to ""result [ab while nresult append(asee below ab ba+ return result fib ( call it write the result [ this exampleas usualdemonstrates some new python featuresthe return statement returns with value from function return without an expression argument returns none falling off the end of function also returns none the statement result append(acalls method of the list object result method is function that 'belongsto an object and is named obj methodnamewhere obj is some object (this may be an actuallycall by object reference would be better descriptionsince if mutable object is passedthe caller will see any changes the callee makes to it (items inserted into list defining functions |
2,110 | expression)and methodname is the name of method that is defined by the object' type different types define different methods methods of different types may have the same name without causing ambiguity (it is possible to define your own object types and methodsusing classessee classesthe method append(shown in the example is defined for list objectsit adds new element at the end of the list in this example it is equivalent to result result [ ]but more efficient more on defining functions it is also possible to define functions with variable number of arguments there are three formswhich can be combined default argument values the most useful form is to specify default value for one or more arguments this creates function that can be called with fewer arguments than it is defined to allow for exampledef ask_ok(promptretries= reminder='please try again!')while trueok input(promptif ok in (' ''ye''yes')return true if ok in (' ''no''nop''nope')return false retries retries if retries raise valueerror('invalid user response'print(reminderthis function can be called in several waysgiving only the mandatory argumentask_ok('do you really want to quit?'giving one of the optional argumentsask_ok('ok to overwrite the file?' or even giving all argumentsask_ok('ok to overwrite the file?' 'come ononly yes or no!'this example also introduces the in keyword this tests whether or not sequence contains certain value the default values are evaluated at the point of function definition in the defining scopeso that def (arg= )print(argi (will print important warningthe default value is evaluated only once this makes difference when the default is mutable object such as listdictionaryor instances of most classes for examplethe following function accumulates the arguments passed to it on subsequent calls more control flow tools |
2,111 | def (al=[]) append(areturn print( ( )print( ( )print( ( )this will print [ [ [ if you don' want the default to be shared between subsequent callsyou can write the function like this insteaddef (al=none)if is nonel [ append(areturn keyword arguments functions can also be called using keyword arguments of the form kwarg=value for instancethe following functiondef parrot(voltagestate=' stiff'action='voom'type='norwegian blue')print("-this parrot wouldn' "actionend='print("if you put"voltage"volts through it "print("-lovely plumagethe"typeprint("-it' "state"!"accepts one required argument (voltageand three optional arguments (stateactionand typethis function can be called in any of the following waysparrot( parrot(voltage= parrot(voltage= action='vooooom'parrot(action='vooooom'voltage= parrot(' million''bereft of life''jump'parrot(' thousand'state='pushing up the daisies' positional argument keyword argument keyword arguments keyword arguments positional arguments positional keyword but all the following calls would be invalidparrot(parrot(voltage= 'dead'parrot( voltage= parrot(actor='john cleese'required argument missing non-keyword argument after keyword argument duplicate value for the same argument unknown keyword argument in function callkeyword arguments must follow positional arguments all the keyword arguments passed must match one of the arguments accepted by the function ( actor is not valid argument for the parrot function)and their order is not important this also includes non-optional arguments ( parrot(voltage= is valid toono argument may receive value more than once here' an example that fails due to this restriction more on defining functions |
2,112 | def function( )pass function( = traceback (most recent call last)file ""line in typeerrorfunction(got multiple values for keyword argument 'awhen final formal parameter of the form **name is presentit receives dictionary (see typesmappingcontaining all keyword arguments except for those corresponding to formal parameter this may be combined with formal parameter of the form *name (described in the next subsectionwhich receives tuple containing the positional arguments beyond the formal parameter list (*name must occur before **name for exampleif we define function like thisdef cheeseshop(kind*arguments**keywords)print("-do you have any"kind"?"print("- ' sorrywe're all out of"kindfor arg in argumentsprint(argprint("- for kw in keywordsprint(kw":"keywords[kw]it could be called like thischeeseshop("limburger""it' very runnysir ""it' really veryvery runnysir "shopkeeper="michael palin"client="john cleese"sketch="cheese shop sketch"and of course it would print-do you have any limburger - ' sorrywe're all out of limburger it' very runnysir it' really veryvery runnysir shopkeeper michael palin client john cleese sketch cheese shop sketch note that the order in which the keyword arguments are printed is guaranteed to match the order in which they were provided in the function call arbitrary argument lists finallythe least frequently used option is to specify that function can be called with an arbitrary number of arguments these arguments will be wrapped up in tuple (see tuples and sequencesbefore the variable number of argumentszero or more normal arguments may occur def write_multiple_items(fileseparator*args)file write(separator join(args)normallythese variadic arguments will be last in the list of formal parametersbecause they scoop up all remaining input arguments that are passed to the function any formal parameters which occur after more control flow tools |
2,113 | the *args parameter are 'keyword-onlyargumentsmeaning that they can only be used as keywords rather than positional arguments def concat(*argssep="/")return sep join(argsconcat("earth""mars""venus"'earth/mars/venusconcat("earth""mars""venus"sep="'earth mars venusunpacking argument lists the reverse situation occurs when the arguments are already in list or tuple but need to be unpacked for function call requiring separate positional arguments for instancethe built-in range(function expects separate start and stop arguments if they are not available separatelywrite the function call with the *-operator to unpack the arguments out of list or tuplelist(range( )[ args [ list(range(*args)[ normal call with separate arguments call with arguments unpacked from list in the same fashiondictionaries can deliver keyword arguments with the **-operatordef parrot(voltagestate=' stiff'action='voom')print("-this parrot wouldn' "actionend='print("if you put"voltage"volts through it "end='print(" ' "state"!" {"voltage""four million""state""bleedindemised""action""voom"parrot(** -this parrot wouldn' voom if you put four million volts through it ' bleedindemised lambda expressions small anonymous functions can be created with the lambda keyword this function returns the sum of its two argumentslambda aba+ lambda functions can be used wherever function objects are required they are syntactically restricted to single expression semanticallythey are just syntactic sugar for normal function definition like nested function definitionslambda functions can reference variables from the containing scopedef make_incrementor( )return lambda xx make_incrementor( ( ( the above example uses lambda expression to return function another use is to pass small function as an argument more on defining functions |
2,114 | pairs [( 'one')( 'two')( 'three')( 'four')pairs sort(key=lambda pairpair[ ]pairs [( 'four')( 'one')( 'three')( 'two')documentation strings here are some conventions about the content and formatting of documentation strings the first line should always be shortconcise summary of the object' purpose for brevityit should not explicitly state the object' name or typesince these are available by other means (except if the name happens to be verb describing function' operationthis line should begin with capital letter and end with period if there are more lines in the documentation stringthe second line should be blankvisually separating the summary from the rest of the description the following lines should be one or more paragraphs describing the object' calling conventionsits side effectsetc the python parser does not strip indentation from multi-line string literals in pythonso tools that process documentation have to strip indentation if desired this is done using the following convention the first non-blank line after the first line of the string determines the amount of indentation for the entire documentation string (we can' use the first line since it is generally adjacent to the string' opening quotes so its indentation is not apparent in the string literal whitespace "equivalentto this indentation is then stripped from the start of all lines of the string lines that are indented less should not occurbut if they occur all their leading whitespace should be stripped equivalence of whitespace should be tested after expansion of tabs (to spacesnormallyhere is an example of multi-line docstringdef my_function()"""do nothingbut document it noreallyit doesn' do anything ""pass print(my_function __doc__do nothingbut document it noreallyit doesn' do anything function annotations function annotations are completely optional metadata information about the types used by user-defined functions (see pep and pep for more informationannotations are stored in the __annotations__ attribute of the function as dictionary and have no effect on any other part of the function parameter annotations are defined by colon after the parameter namefollowed by an expression evaluating to the value of the annotation return annotations are defined by literal ->followed by an expressionbetween the parameter list and the colon denoting the end of the def statement the following example has positional argumenta keyword argumentand the return value annotateddef (hamstreggsstr 'eggs'-strprint("annotations:" __annotations__(continues on next page more control flow tools |
2,115 | (continued from previous pageprint("arguments:"hameggsreturn ham and eggs ('spam'annotations{'ham''return''eggs'argumentsspam eggs 'spam and eggs intermezzocoding style now that you are about to write longermore complex pieces of pythonit is good time to talk about coding style most languages can be written (or more conciseformattedin different stylessome are more readable than others making it easy for others to read your code is always good ideaand adopting nice coding style helps tremendously for that for pythonpep has emerged as the style guide that most projects adhere toit promotes very readable and eye-pleasing coding style every python developer should read it at some pointhere are the most important points extracted for youuse -space indentationand no tabs spaces are good compromise between small indentation (allows greater nesting depthand large indentation (easier to readtabs introduce confusionand are best left out wrap lines so that they don' exceed characters this helps users with small displays and makes it possible to have several code files side-by-side on larger displays use blank lines to separate functions and classesand larger blocks of code inside functions when possibleput comments on line of their own use docstrings use spaces around operators and after commasbut not directly inside bracketing constructsa ( ( name your classes and functions consistentlythe convention is to use camelcase for classes and lower_case_with_underscores for functions and methods always use self as the name for the first method argument (see first look at classes for more on classes and methodsdon' use fancy encodings if your code is meant to be used in international environments python' defaultutf- or even plain ascii work best in any case likewisedon' use non-ascii characters in identifiers if there is only the slightest chance people speaking different language will read or maintain the code intermezzocoding style |
2,116 | more control flow tools |
2,117 | five data structures this describes some things you've learned about already in more detailand adds some new things as well more on lists the list data type has some more methods here are all of the methods of list objectslist append(xadd an item to the end of the list equivalent to [len( ):[xlist extend(iterableextend the list by appending all the items from the iterable equivalent to [len( ):iterable list insert(ixinsert an item at given position the first argument is the index of the element before which to insertso insert( xinserts at the front of the listand insert(len( )xis equivalent to append(xlist remove(xremove the first item from the list whose value is equal to it raises valueerror if there is no such item list pop([ ]remove the item at the given position in the listand return it if no index is specifieda pop(removes and returns the last item in the list (the square brackets around the in the method signature denote that the parameter is optionalnot that you should type square brackets at that position you will see this notation frequently in the python library reference list clear(remove all items from the list equivalent to del [:list index( [start [end ]]return zero-based index in the list of the first item whose value is equal to raises valueerror if there is no such item the optional arguments start and end are interpreted as in the slice notation and are used to limit the search to particular subsequence of the list the returned index is computed relative to the beginning of the full sequence rather than the start argument list count(xreturn the number of times appears in the list list sort(key=nonereverse=falsesort the items of the list in place (the arguments can be used for sort customizationsee sorted(for their explanation |
2,118 | list reverse(reverse the elements of the list in place list copy(return shallow copy of the list equivalent to [:an example that uses most of the list methodsfruits ['orange''apple''pear''banana''kiwi''apple''banana'fruits count('apple' fruits count('tangerine' fruits index('banana' fruits index('banana' find next banana starting position fruits reverse(fruits ['banana''apple''kiwi''banana''pear''apple''orange'fruits append('grape'fruits ['banana''apple''kiwi''banana''pear''apple''orange''grape'fruits sort(fruits ['apple''apple''banana''banana''grape''kiwi''orange''pear'fruits pop('pearyou might have noticed that methods like insertremove or sort that only modify the list have no return value printed they return the default none this is design principle for all mutable data structures in python using lists as stacks the list methods make it very easy to use list as stackwhere the last element added is the first element retrieved ("last-infirst-out"to add an item to the top of the stackuse append(to retrieve an item from the top of the stackuse pop(without an explicit index for examplestack [ stack append( stack append( stack [ stack pop( stack [ stack pop( stack pop( stack [ other languages may return ->insert(" ")->remove(" ")->sort() the mutated objectwhich allows method chainingsuch as data structures |
2,119 | using lists as queues it is also possible to use list as queuewhere the first element added is the first element retrieved ("first-infirst-out")howeverlists are not efficient for this purpose while appends and pops from the end of list are fastdoing inserts or pops from the beginning of list is slow (because all of the other elements have to be shifted by oneto implement queueuse collections deque which was designed to have fast appends and pops from both ends for examplefrom collections import deque queue deque(["eric""john""michael"]queue append("terry"terry arrives queue append("graham"graham arrives queue popleft(the first to arrive now leaves 'ericqueue popleft(the second to arrive now leaves 'johnqueue remaining queue in order of arrival deque(['michael''terry''graham']list comprehensions list comprehensions provide concise way to create lists common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterableor to create subsequence of those elements that satisfy certain condition for exampleassume we want to create list of squareslikesquares [for in range( )squares append( ** squares [ note that this creates (or overwritesa variable named that still exists after the loop completes we can calculate the list of squares without any side effects usingsquares list(map(lambda xx** range( ))orequivalentlysquares [ ** for in range( )which is more concise and readable list comprehension consists of brackets containing an expression followed by for clausethen zero or more for or if clauses the result will be new list resulting from evaluating the expression in the context of the for and if clauses which follow it for examplethis listcomp combines the elements of two lists if they are not equal[(xyfor in [ , , for in [ , , if ! [( )( )( )( )( )( )( )and it' equivalent to more on lists |
2,120 | combs [for in [ , , ]for in [ , , ]if !ycombs append((xy)combs [( )( )( )( )( )( )( )note how the order of the for and if statements is the same in both these snippets if the expression is tuple ( the (xyin the previous example)it must be parenthesized vec [- - create new list with the values doubled [ * for in vec[- - filter the list to exclude negative numbers [ for in vec if > [ apply function to all the elements [abs(xfor in vec[ call method on each element freshfruit [banana'loganberry ''passion fruit '[weapon strip(for weapon in freshfruit['banana''loganberry''passion fruit'create list of -tuples like (numbersquare[(xx** for in range( )[( )( )( )( )( )( )the tuple must be parenthesizedotherwise an error is raised [xx** for in range( )file ""line in [xx** for in range( )syntaxerrorinvalid syntax flatten list using listcomp with two 'forvec [[ , , ][ , , ][ , , ][num for elem in vec for num in elem[ list comprehensions can contain complex expressions and nested functionsfrom math import pi [str(round(pii)for in range( )[' '' '' '' '' 'nested list comprehensions the initial expression in list comprehension can be any arbitrary expressionincluding another list comprehension consider the following example of matrix implemented as list of lists of length matrix [ ][ ](continues on next page data structures |
2,121 | (continued from previous page[ ]the following list comprehension will transpose rows and columns[[row[ifor row in matrixfor in range( )[[ ][ ][ ][ ]as we saw in the previous sectionthe nested listcomp is evaluated in the context of the for that follows itso this example is equivalent totransposed [for in range( )transposed append([row[ifor row in matrix]transposed [[ ][ ][ ][ ]whichin turnis the same astransposed [for in range( )the following lines implement the nested listcomp transposed_row [for row in matrixtransposed_row append(row[ ]transposed append(transposed_rowtransposed [[ ][ ][ ][ ]in the real worldyou should prefer built-in functions to complex flow statements the zip(function would do great job for this use caselist(zip(*matrix)[( )( )( )( )see unpacking argument lists for details on the asterisk in this line the del statement there is way to remove an item from list given its index instead of its valuethe del statement this differs from the pop(method which returns value the del statement can also be used to remove slices from list or clear the entire list (which we did earlier by assignment of an empty list to the slicefor examplea [- del [ [ del [ : [ del [:(continues on next page the del statement |
2,122 | (continued from previous pagea [del can also be used to delete entire variablesdel referencing the name hereafter is an error (at least until another value is assigned to itwe'll find other uses for del later tuples and sequences we saw that lists and strings have many common propertiessuch as indexing and slicing operations they are two examples of sequence data types (see typesseqsince python is an evolving languageother sequence data types may be added there is also another standard sequence data typethe tuple tuple consists of number of values separated by commasfor instancet 'hello! [ ( 'hello!'tuples may be nestedu ( (( 'hello!')( )tuples are immutablet[ traceback (most recent call last)file ""line in typeerror'tupleobject does not support item assignment but they can contain mutable objectsv ([ ][ ] ([ ][ ]as you seeon output tuples are always enclosed in parenthesesso that nested tuples are interpreted correctlythey may be input with or without surrounding parenthesesalthough often parentheses are necessary anyway (if the tuple is part of larger expressionit is not possible to assign to the individual items of tuplehowever it is possible to create tuples which contain mutable objectssuch as lists though tuples may seem similar to liststhey are often used in different situations and for different purposes tuples are immutableand usually contain heterogeneous sequence of elements that are accessed via unpacking (see later in this sectionor indexing (or even by attribute in the case of namedtupleslists are mutableand their elements are usually homogeneous and are accessed by iterating over the list special problem is the construction of tuples containing or itemsthe syntax has some extra quirks to accommodate these empty tuples are constructed by an empty pair of parenthesesa tuple with one item is constructed by following value with comma (it is not sufficient to enclose single value in parenthesesuglybut effective for exampleempty (singleton 'hello'len(empty<-note trailing comma (continues on next page data structures |
2,123 | (continued from previous page len(singleton singleton ('hello',the statement 'hello!is an example of tuple packingthe values and 'hello!are packed together in tuple the reverse operation is also possiblexyz this is calledappropriately enoughsequence unpacking and works for any sequence on the right-hand side sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence note that multiple assignment is really just combination of tuple packing and sequence unpacking sets python also includes data type for sets set is an unordered collection with no duplicate elements basic uses include membership testing and eliminating duplicate entries set objects also support mathematical operations like unionintersectiondifferenceand symmetric difference curly braces or the set(function can be used to create sets noteto create an empty set you have to use set()not {}the latter creates an empty dictionarya data structure that we discuss in the next section here is brief demonstrationbasket {'apple''orange''apple''pear''orange''banana'print(basketshow that duplicates have been removed {'orange''banana''pear''apple''orangein basket fast membership testing true 'crabgrassin basket false demonstrate set operations on unique letters from two words set('abracadabra' set('alacazam' unique letters in {' '' '' '' '' ' letters in but not in {' '' '' ' letters in or or both {' '' '' '' '' '' '' '' ' letters in both and {' '' ' letters in or but not both {' '' '' '' '' '' 'similarly to list comprehensionsset comprehensions are also supporteda { for in 'abracadabraif not in 'abc' {' '' ' sets |
2,124 | dictionaries another useful data type built into python is the dictionary (see typesmappingdictionaries are sometimes found in other languages as "associative memoriesor "associative arraysunlike sequenceswhich are indexed by range of numbersdictionaries are indexed by keyswhich can be any immutable typestrings and numbers can always be keys tuples can be used as keys if they contain only stringsnumbersor tuplesif tuple contains any mutable object either directly or indirectlyit cannot be used as key you can' use lists as keyssince lists can be modified in place using index assignmentsslice assignmentsor methods like append(and extend(it is best to think of dictionary as set of keyvalue pairswith the requirement that the keys are unique (within one dictionarya pair of braces creates an empty dictionary{placing comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionarythis is also the way dictionaries are written on output the main operations on dictionary are storing value with some key and extracting the value given the key it is also possible to delete key:value pair with del if you store using key that is already in usethe old value associated with that key is forgotten it is an error to extract value using non-existent key performing list(don dictionary returns list of all the keys used in the dictionaryin insertion order (if you want it sortedjust use sorted(dinsteadto check whether single key is in the dictionaryuse the in keyword here is small example using dictionarytel {'jack' 'sape' tel['guido' tel {'jack' 'sape' 'guido' tel['jack' del tel['sape'tel['irv' tel {'jack' 'guido' 'irv' list(tel['jack''guido''irv'sorted(tel['guido''irv''jack''guidoin tel true 'jacknot in tel false the dict(constructor builds dictionaries directly from sequences of key-value pairsdict([('sape' )('guido' )('jack' )]{'sape' 'guido' 'jack' in additiondict comprehensions can be used to create dictionaries from arbitrary key and value expressions{xx** for in ( ){ when the keys are simple stringsit is sometimes easier to specify pairs using keyword argumentsdict(sape= guido= jack= {'sape' 'guido' 'jack' data structures |
2,125 | looping techniques when looping through dictionariesthe key and corresponding value can be retrieved at the same time using the items(method knights {'gallahad''the pure''robin''the brave'for kv in knights items()print(kvgallahad the pure robin the brave when looping through sequencethe position index and corresponding value can be retrieved at the same time using the enumerate(function for iv in enumerate(['tic''tac''toe'])print(iv tic tac toe to loop over two or more sequences at the same timethe entries can be paired with the zip(function questions ['name''quest''favorite color'answers ['lancelot''the holy grail''blue'for qa in zip(questionsanswers)print('what is your { }it is { format(qa)what is your nameit is lancelot what is your questit is the holy grail what is your favorite colorit is blue to loop over sequence in reversefirst specify the sequence in forward direction and then call the reversed(function for in reversed(range( ))print( to loop over sequence in sorted orderuse the sorted(function which returns new sorted list while leaving the source unaltered basket ['apple''orange''apple''pear''orange''banana'for in sorted(set(basket))print(fapple banana orange pear looping techniques |
2,126 | it is sometimes tempting to change list while you are looping over ithoweverit is often simpler and safer to create new list instead import math raw_data [ float('nan') float('nan') filtered_data [for value in raw_dataif not math isnan(value)filtered_data append(valuefiltered_data [ more on conditions the conditions used in while and if statements can contain any operatorsnot just comparisons the comparison operators in and not in check whether value occurs (does not occurin sequence the operators is and is not compare whether two objects are really the same objectthis only matters for mutable objects like lists all comparison operators have the same prioritywhich is lower than that of all numerical operators comparisons can be chained for examplea = tests whether is less than and moreover equals comparisons may be combined using the boolean operators and and orand the outcome of comparison (or of any other boolean expressionmay be negated with not these have lower priorities than comparison operatorsbetween themnot has the highest priority and or the lowestso that and not or is equivalent to ( and (not )or as alwaysparentheses can be used to express the desired composition the boolean operators and and or are so-called short-circuit operatorstheir arguments are evaluated from left to rightand evaluation stops as soon as the outcome is determined for exampleif and are true but is falsea and and does not evaluate the expression when used as general value and not as booleanthe return value of short-circuit operator is the last evaluated argument it is possible to assign the result of comparison or other boolean expression to variable for examplestring string string '''trondheim''hammer dancenon_null string or string or string non_null 'trondheimnote that in pythonunlike cassignment cannot occur inside expressions programmers may grumble about thisbut it avoids common class of problems encountered in programstyping in an expression when =was intended comparing sequences and other types sequence objects may be compared to other objects with the same sequence type the comparison uses lexicographical orderingfirst the first two items are comparedand if they differ this determines the outcome of the comparisonif they are equalthe next two items are comparedand so onuntil either sequence is exhausted if two items to be compared are themselves sequences of the same typethe lexicographical comparison is carried out recursively if all items of two sequences compare equalthe sequences are considered equal if one sequence is an initial sub-sequence of the otherthe shorter sequence is the smaller (lesser data structures |
2,127 | one lexicographical ordering for strings uses the unicode code point number to order individual characters some examples of comparisons between sequences of the same type( ( [ [ 'abc' 'pascal'python( ( ( ( - ( =( ( ('abc'' ') ( ('aa''ab')note that comparing objects of different types with is legal provided that the objects have appropriate comparison methods for examplemixed numeric types are compared according to their numeric valueso equals etc otherwiserather than providing an arbitrary orderingthe interpreter will raise typeerror exception comparing sequences and other types |
2,128 | data structures |
2,129 | six modules if you quit from the python interpreter and enter it againthe definitions you have made (functions and variablesare lost thereforeif you want to write somewhat longer programyou are better off using text editor to prepare the input for the interpreter and running it with that file as input instead this is known as creating script as your program gets longeryou may want to split it into several files for easier maintenance you may also want to use handy function that you've written in several programs without copying its definition into each program to support thispython has way to put definitions in file and use them in script or in an interactive instance of the interpreter such file is called moduledefinitions from module can be imported into other modules or into the main module (the collection of variables that you have access to in script executed at the top level and in calculator modea module is file containing python definitions and statements the file name is the module name with the suffix py appended within modulethe module' name (as stringis available as the value of the global variable __name__ for instanceuse your favorite text editor to create file called fibo py in the current directory with the following contentsfibonacci numbers module def fib( )write fibonacci series up to ab while nprint(aend='ab ba+ print(def fib ( )return fibonacci series up to result [ab while nresult append(aab ba+ return result now enter the python interpreter and import this module with the following commandimport fibo this does not enter the names of the functions defined in fibo directly in the current symbol tableit only enters the module name fibo there using the module name you can access the functionsfibo fib( fibo fib ( (continues on next page |
2,130 | (continued from previous page[ fibo __name__ 'fiboif you intend to use function often you can assign it to local namefib fibo fib fib( more on modules 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 name is encountered in an import statement (they are also run if the file is executed as script each module has its own private symbol tablewhich is used as the global symbol table by all functions defined in the module thusthe author of module can use global variables in the module without worrying about accidental clashes with user' global variables on the other handif you know what you are doing you can touch module' global variables with the same notation used to refer to its functionsmodname itemname modules can import other modules it is customary but not required to place all import statements at the beginning of module (or scriptfor that matterthe imported module names are placed in the importing module' global symbol table there is variant of the import statement that imports names from module directly into the importing module' symbol table for examplefrom fibo import fibfib fib( this does not introduce the module name from which the imports are taken in the local symbol table (so in the examplefibo is not definedthere is even variant to import all names that module definesfrom fibo import fib( this imports all names except those beginning with an underscore (_in most cases python programmers do not use this facility since it introduces an unknown set of names into the interpreterpossibly hiding some things you have already defined note that in general the practice of importing from module or package is frowned uponsince it often causes poorly readable code howeverit is okay to use it to save typing in interactive sessions if the module name is followed by asthen the name following as is bound directly to the imported module import fibo as fib fib fib( in fact function definitions are also 'statementsthat are 'executed'the execution of module-level function definition enters the function name in the module' global symbol table modules |
2,131 | this is effectively importing the module in the same way that import fibo will dowith the only difference of it being available as fib it can also be used when utilising from with similar effectsfrom fibo import fib as fibonacci fibonacci( notefor efficiency reasonseach module is only imported once per interpreter session thereforeif you change your modulesyou must restart the interpreter orif it' just one module you want to test interactivelyuse importlib reload() import importlibimportlib reload(modulenameexecuting modules as scripts when you run python module with python fibo py the code in the module will be executedjust as if you imported itbut with the __name__ set to "__main__that means that by adding this code at the end of your moduleif __name__ ="__main__"import sys fib(int(sys argv[ ])you can make the file usable as script as well as an importable modulebecause the code that parses the command line only runs if the module is executed as the "mainfilepython fibo py if the module is importedthe code is not runimport fibo this is often used either to provide convenient user interface to moduleor for testing purposes (running the module as script executes test suitethe module search path when module named spam is importedthe interpreter first searches for built-in module with that name if not foundit then searches for file named spam py in list of directories given by the variable sys path sys path is initialized from these locationsthe directory containing the input script (or the current directory when no file is specifiedpythonpath ( list of directory nameswith the same syntax as the shell variable paththe installation-dependent default noteon file systems which support symlinksthe directory containing the input script is calculated after the symlink is followed in other words the directory containing the symlink is not added to the module more on modules |
2,132 | search path after initializationpython programs can modify sys path the directory containing the script being run is placed at the beginning of the search pathahead of the standard library path this means that scripts in that directory will be loaded instead of modules of the same name in the library directory this is an error unless the replacement is intended see section standard modules for more information "compiledpython files to speed up loading modulespython caches the compiled version of each module in the __pycache__ directory under the name module version pycwhere the version encodes the format of the compiled fileit generally contains the python version number for examplein cpython release the compiled version of spam py would be cached as __pycache__/spam cpython- 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' out of date and needs to be recompiled this is completely automatic process alsothe compiled modules are platform-independentso the same library can be shared among systems with different architectures python does not check the cache in two circumstances firstit always recompiles and does not store the result for the module that' loaded directly from the command line secondit does not check the cache if there is no source module to support non-source (compiled onlydistributionthe compiled module must be in the source directoryand there must not be source module some tips for expertsyou can use the - or -oo switches on the python command to reduce the size of compiled module the - switch removes assert statementsthe -oo switch removes both assert statements and __doc__ strings since some programs may rely on having these availableyou should only use this option if you know what you're doing "optimizedmodules have an opttag and are usually smaller future releases may change the effects of optimization program doesn' run any faster when it is read from pyc file than when it is read from py filethe only thing that' faster about pyc files is the speed with which they are loaded the module compileall can create pyc files for all modules in directory there is more detail on this processincluding flow chart of the decisionsin pep standard modules python comes with library of standard modulesdescribed in separate documentthe python library reference ("library referencehereaftersome modules are built into the interpreterthese provide access to operations that are not part of the core of the language but are nevertheless built ineither for efficiency or to provide access to operating system primitives such as system calls the set of such modules is configuration option which also depends on the underlying platform for examplethe winreg module is only provided on windows systems one particular module deserves some attentionsyswhich is built into every python interpreter the variables sys ps and sys ps define the strings used as primary and secondary promptsimport sys sys ps sys ps (continues on next page modules |
2,133 | (continued from previous pagesys ps 'ccprint('yuck!'yuckcthese two variables are only defined if the interpreter is in interactive mode the variable sys path is list of strings that determines the interpreter' search path for modules it is initialized to default path taken from the environment variable pythonpathor from built-in default if pythonpath is not set you can modify it using standard list operationsimport sys sys path append('/ufs/guido/lib/python' the dir(function the built-in function dir(is used to find out which names module defines it returns sorted list of stringsimport fibosys dir(fibo['__name__''fib''fib 'dir(sys['__displayhook__''__doc__''__excepthook__''__loader__''__name__''__package__''__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''implementation''int_info''intern''maxsize''maxunicode''meta_path''modules''path''path_hooks''path_importer_cache''platform''prefix''ps ''setcheckinterval''setdlopenflags''setprofile''setrecursionlimit''setswitchinterval''settrace''stderr''stdin''stdout''thread_info''version''version_info''warnoptions'without argumentsdir(lists the names you have defined currentlya [ import fibo fib fibo fib dir(['__builtins__''__name__'' ''fib''fibo''sys'note that it lists all types of namesvariablesmodulesfunctionsetc dir(does not list the names of built-in functions and variables if you want list of thosethey are defined in the standard module builtins the dir(function |
2,134 | import builtins dir(builtins['arithmeticerror''assertionerror''attributeerror''baseexception''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''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' packages packages are way of structuring python' module namespace by using "dotted module namesfor examplethe module name designates submodule named in package named just like the use of modules saves the authors of different modules from having to worry about each other' global variable namesthe use of dotted module names saves the authors of multi-module packages like numpy or pillow from having to worry about each other' module names suppose you want to design collection of modules ( "package"for the uniform handling of sound files and sound data there are many different sound file formats (usually recognized by their extensionfor examplewavaiffau)so you may need to create and maintain growing collection of modules for the conversion between the various file formats there are also many different operations you might want to perform on sound data (such as mixingadding echoapplying an equalizer functioncreating an artificial stereo effect)so in addition you will be writing never-ending stream of modules to perform these operations here' possible structure for your package (expressed in terms of hierarchical filesystem)sound__init__ py formats__init__ py wavread py wavwrite py top-level package initialize the sound package subpackage for file format conversions (continues on next page modules |
2,135 | (continued from previous pageaiffread py aiffwrite py auread py auwrite py effectssubpackage for sound effects __init__ py echo py surround py reverse py filterssubpackage for filters __init__ py equalizer py vocoder py karaoke py when importing the packagepython searches through the directories on sys path looking for the package subdirectory the __init__ py files are required to make python treat the directories as containing packagesthis is done to prevent directories with common namesuch as stringfrom unintentionally hiding valid modules that occur later on the module search path in the simplest case__init__ py can just be an empty filebut it can also execute initialization code for the package or set the __all__ variabledescribed later users of the package can import individual modules from the packagefor exampleimport sound effects echo this loads the submodule sound effects echo it must be referenced with its full name sound effects echo echofilter(inputoutputdelay= atten= an alternative way of importing the submodule isfrom sound effects import echo this also loads the submodule echoand makes it available without its package prefixso it can be used as followsecho echofilter(inputoutputdelay= atten= yet another variation is to import the desired function or variable directlyfrom sound effects echo import echofilter againthis loads the submodule echobut this makes its function echofilter(directly availableechofilter(inputoutputdelay= atten= note that when using from package import itemthe item can be either submodule (or subpackageof the packageor some other name defined in the packagelike functionclass or variable the import statement first tests whether the item is defined in the packageif notit assumes it is module and attempts to load it if it fails to find itan importerror exception is raised contrarilywhen using syntax like import item subitem subsubitemeach item except for the last must be packagethe last item can be module or package but can' be class or function or variable defined packages |
2,136 | in the previous item importing from package now what happens when the user writes from sound effects import *ideallyone would hope that this somehow goes out to the filesystemfinds which submodules are present in the packageand imports them all this could take long time and importing sub-modules might have unwanted side-effects that should only happen when the sub-module is explicitly imported the only solution is for the package author to provide an explicit index of the package the import statement uses the following conventionif package' __init__ py code defines list named __all__it is taken to be the 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 new version of the package is released package authors may also decide not to support itif they don' see use for importing from their package for examplethe file sound/effects/__init__ py could contain the following code__all__ ["echo""surround""reverse"this would mean that from sound effects import would import the three named submodules of the sound package if __all__ is not definedthe statement from sound effects import does not import all submodules from the package sound effects into the current namespaceit only ensures that the package sound effects has been imported (possibly running any initialization code in __init__ pyand then imports whatever names are defined in the package this includes any names defined (and submodules explicitly loadedby __init__ py it also includes any submodules of the package that were explicitly loaded by previous import statements consider this codeimport sound effects echo import sound effects surround from sound effects import in this examplethe echo and surround modules are imported in the current namespace because they are defined in the sound effects package when the from import statement is executed (this also works when __all__ is defined although certain modules are designed to export only names that follow certain patterns when you use import *it is still considered bad practice in production code rememberthere is nothing wrong with using from package import specific_submodulein factthis is the recommended notation unless the importing module needs to use submodules with the same name from different packages intra-package references when packages are structured into subpackages (as with the sound package in the example)you can use absolute imports to refer to submodules of siblings packages for exampleif the module sound filters vocoder needs to use the echo module in the sound effects packageit can use from sound effects import echo you can also write relative importswith the from module import name form of import statement these imports use leading dots to indicate the current and parent packages involved in the relative import from the surround module for exampleyou might use modules |
2,137 | from import echo from import formats from filters import equalizer note that relative imports are based on the name of the current module since the name of the main module is always "__main__"modules intended for use as the main module of python application must always use absolute imports packages in multiple directories packages support one more special attribute__path__ this is initialized to be list containing the name of the directory holding the package' __init__ py before the code in that file is executed this variable can be modifieddoing so affects future searches for modules and subpackages contained in the package while this feature is not often neededit can be used to extend the set of modules found in package packages |
2,138 | modules |
2,139 | seven input and output there are several ways to present the output of programdata can be printed in human-readable formor written to file for future use this will discuss some of the possibilities fancier output formatting so far we've encountered two ways of writing valuesexpression statements and the print(function ( third way is using the write(method of file objectsthe standard output file can be referenced as sys stdout see the library reference for more information on this often you'll want more control over the formatting of your output than simply printing space-separated values there are several ways to format output to use formatted string literalsbegin string with or before the opening quotation mark or triple quotation mark inside this stringyou can write python expression between and characters that can refer to variables or literal values year event 'referendumf'results of the {year{event}'results of the referendumthe str format(method of strings requires more manual effort you'll still use and to mark where variable will be substituted and can provide detailed formatting directivesbut you'll also need to provide the information to be formatted yes_votes no_votes percentage yes_votes/(yes_votes+no_votes'{:- yes votes {: %}format(yes_votespercentage yes votes %finallyyou can do all the string handling yourself by using string slicing and concatenation operations to create any layout you can imagine the string type has some methods that perform useful operations for padding strings to given column width when you don' need fancy output but just want quick display of some variables for debugging purposesyou can convert any value to string with the repr(or str(functions the str(function is meant to return representations of values which are fairly human-readablewhile repr(is meant to generate representations which can be read by the interpreter (or will force syntaxerror if there is no equivalent syntaxfor objects which don' have particular representation for human consumptionstr(will return the same value as repr(many valuessuch as numbers or structures like lists and dictionarieshave the same representation using either function stringsin particularhave two distinct representations some examples |
2,140 | 'helloworld str( 'helloworld repr( "'helloworld 'str( / ' 'the value of is repr( 'and is repr(yprint(sthe value of is and is the repr(of string adds string quotes and backslasheshello 'helloworld\nhellos repr(helloprint(hellos'helloworld\nthe argument to repr(may be any python objectrepr((xy('spam''eggs'))"( ('spam''eggs'))the string module contains template class that offers yet another way to substitute values into stringsusing placeholders like $ and replacing them with values from dictionarybut offers much less control of the formatting formatted string literals formatted string literals (also called -strings for shortlet you include the value of python expressions inside string by prefixing the string with or and writing expressions as {expressionan optional format specifier can follow the expression this allows greater control over how the value is formatted the following example rounds pi to three places after the decimalimport math print( 'the value of pi is approximately {math pi 'passing an integer after the ':will cause that field to be minimum number of characters wide this is useful for making columns line up table {'sjoerd' 'jack' 'dcab' for namephone in table items()print( '{name: =={phone: }'sjoerd == jack == dcab == other modifiers can be used to convert the value before it is formatted '!aapplies ascii()'!sapplies str()and '!rapplies repr()animals 'eelsprint( 'my hovercraft is full of {animals'my hovercraft is full of eels print('my hovercraft is full of {animals ! 'my hovercraft is full of 'eelsfor reference on these format specificationssee the reference guide for the formatspec input and output |
2,141 | the string format(method basic usage of the str format(method looks like thisprint('we are the {who say "{}!"format('knights''ni')we are the knights who say "ni!the brackets and characters within them (called format fieldsare replaced with the objects passed into the str format(method number in the brackets can be used to refer to the position of the object passed into the str format(method print('{ and { }format('spam''eggs')spam and eggs print('{ and { }format('spam''eggs')eggs and spam if keyword arguments are used in the str format(methodtheir values are referred to by using the name of the argument print('this {foodis {adjectiveformatfood='spam'adjective='absolutely horrible')this spam is absolutely horrible positional and keyword arguments can be arbitrarily combinedprint('the story of { }{ }and {otherformat('bill''manfred'other='georg')the story of billmanfredand georg if you have really long format string that you don' want to split upit would be nice if you could reference the variables to be formatted by name instead of by position this can be done by simply passing the dict and using square brackets '[]to access the keys table {'sjoerd' 'jack' 'dcab' print('jack{ [jack]: }sjoerd{ [sjoerd]: }'dcab{ [dcab]: }format(table)jack sjoerd dcab this could also be done by passing the table as keyword arguments with the '**notation table {'sjoerd' 'jack' 'dcab' print('jack{jack: }sjoerd{sjoerd: }dcab{dcab: }format(**table)jack sjoerd dcab this is particularly useful in combination with the built-in function vars()which returns dictionary containing all local variables as an examplethe following lines produce tidily-aligned set of columns giving integers and their squares and cubesfor in range( )print('{ : { : { : }format(xx*xx* * ) (continues on next page fancier output formatting |
2,142 | (continued from previous page for complete overview of string formatting with str format()see formatstrings manual string formatting here' the same table of squares and cubesformatted manuallyfor in range( )print(repr(xrjust( )repr( *xrjust( )end='note use of 'endon previous line print(repr( * *xrjust( ) (note that the one space between each column was added by the way print(worksit always adds spaces between its arguments the str rjust(method of string objects right-justifies string in field of given width by padding it with spaces on the left there are similar methods str ljust(and str center(these methods do not write anythingthey just return new string if the input string is too longthey don' truncate itbut return it unchangedthis will mess up your column lay-out but that' usually better than the alternativewhich would be lying about value (if you really want truncation you can always add slice operationas in ljust( )[:nthere is another methodstr zfill()which pads numeric string on the left with zeros it understands about plus and minus signs' zfill( ' '- zfill( '- ' zfill( ' old string formatting the operator can also be used for string formatting it interprets the left argument much like sprintf()style format string to be applied to the right argumentand returns the string resulting from this formatting operation for example input and output |
2,143 | import math print('the value of pi is approximately % math pithe value of pi is approximately more information can be found in the old-string-formatting section reading and writing files open(returns file objectand is most commonly used with two argumentsopen(filenamemodef open('workfile'' 'the first argument is string containing the filename the second argument is another string containing few characters describing the way in which the file will be used mode can be 'rwhen the file will only be read'wfor only writing (an existing file with the same name will be erased)and 'aopens the file for appendingany data written to the file is automatically added to the end ' +opens the file for both reading and writing the mode argument is optional'rwill be assumed if it' omitted normallyfiles are opened in text modethat meansyou read and write strings from and to the filewhich are encoded in specific encoding if encoding is not specifiedthe default is platform dependent (see open()'bappended to the mode opens the file in binary modenow the data is read and written in the form of bytes objects this mode should be used for all files that don' contain text in text modethe default when reading is to convert platform-specific line endings (\ on unix\ \ on windowsto just \ when writing in text modethe default is to convert occurrences of \ back to platform-specific line endings this behind-the-scenes modification to file data is fine for text filesbut will corrupt binary data like that in jpeg or exe files be very careful to use binary mode when reading and writing such files it is good practice to use the with keyword when dealing with file objects the advantage is that the file is properly closed after its suite finisheseven if an exception is raised at some point using with is also much shorter than writing equivalent try-finally blockswith open('workfile'as fread_data read( closed true if you're not using the with keywordthen you should call close(to close the file and immediately free up any system resources used by it if you don' explicitly close filepython' garbage collector will eventually destroy the object and close the open file for youbut the file may stay open for while another risk is that different python implementations will do this clean-up at different times after file object is closedeither by with statement or by calling close()attempts to use the file object will automatically fail close( read(traceback (most recent call last)file ""line in valueerrori/ operation on closed file methods of file objects the rest of the examples in this section will assume that file object called has already been created reading and writing files |
2,144 | to read file' contentscall read(size)which reads some quantity of data and returns it as string (in text modeor bytes object (in binary modesize is an optional numeric argument when size is omitted or negativethe entire contents of the file will be read and returnedit' your problem if the file is twice as large as your machine' memory otherwiseat most size bytes are read and returned if the end of the file has been reachedf read(will return an empty string ('' read('this is the entire file \nf read(' readline(reads single line from the filea newline character (\nis left at the end of the stringand is only omitted on the last line of the file if the file doesn' end in newline this makes the return value unambiguousif readline(returns an empty stringthe end of the file has been reachedwhile blank line is represented by '\ ' string containing only single newline readline('this is the first line of the file \nf readline('second line of the file\nf readline('for reading lines from fileyou can loop over the file object this is memory efficientfastand leads to simple codefor line in fprint(lineend=''this is the first line of the file second line of the file if you want to read all the lines of file in list you can also use list(for readlines( write(stringwrites the contents of string to the filereturning the number of characters written write('this is test\ ' other types of objects need to be converted either to string (in text modeor bytes object (in binary modebefore writing themvalue ('the answer' str(valueconvert the tuple to string write( tell(returns an integer giving the file object' 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' positionuse seek(offsetfrom_whatthe position is computed from adding offset to reference pointthe reference point is selected by the from_what argument from_what value of measures from the beginning of the file uses the current file positionand uses the end of the file as the reference point from_what can be omitted and defaults to using the beginning of the file as the reference point open('workfile''rb+' write( ' abcdef'(continues on next page input and output |
2,145 | (continued from previous page seek( read( ' seek(- read( 'dgo to the th byte in the file go to the rd byte before the end in text files (those opened without 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( )and the only valid offset values are those returned from the tell()or zero any other offset value produces undefined behaviour file objects have some additional methodssuch as isatty(and truncate(which are less frequently usedconsult the library reference for complete guide to file objects saving structured data with json strings can easily be written to and read from file numbers take bit more effortsince the read(method only returns stringswhich will have to be passed to function like int()which takes string like ' and returns its numeric value when you want to save more complex data types like nested lists and dictionariesparsing and serializing by hand becomes complicated rather than having users constantly writing and debugging code to save complicated data types to filespython allows you to use the popular data interchange format called json (javascript object notationthe standard module called json can take python data hierarchiesand convert them to string representationsthis process is called serializing reconstructing the data from the string representation is called deserializing between serializing and deserializingthe string representing the object may have been stored in file or dataor sent over network connection to some distant machine notethe json format is commonly used by modern applications to allow for data exchange many programmers are already familiar with itwhich makes it good choice for interoperability if you have an object xyou can view its json string representation with simple line of codeimport json json dumps([ 'simple''list']'[ "simple""list"]another variant of the dumps(functioncalled dump()simply serializes the object to text file so if is text file object opened for writingwe can do thisjson dump(xfto decode the object againif is text file object which has been opened for readingx json load(fthis simple serialization technique can handle lists and dictionariesbut serializing arbitrary class instances in json requires bit of extra effort the reference for the json module contains an explanation of this see alsopickle the pickle module reading and writing files |
2,146 | contrary to json pickle is protocol which allows the serialization of arbitrarily complex python objects as suchit is specific to python and cannot be used to communicate with applications written in other languages it is also insecure by defaultdeserializing pickle data coming from an untrusted source can execute arbitrary codeif the data was crafted by skilled attacker input and output |
2,147 | eight errors and exceptions until now error messages haven' been more than mentionedbut if you have tried out the examples you have probably seen some there are (at leasttwo distinguishable kinds of errorssyntax errors and exceptions syntax errors syntax errorsalso known as parsing errorsare perhaps the most common kind of complaint you get while you are still learning pythonwhile true print('hello world'file ""line while true print('hello world'syntaxerrorinvalid syntax the parser repeats the offending line and displays little 'arrowpointing at the earliest point in the line where the error was detected the error is caused by (or at least detected atthe token preceding the arrowin the examplethe error is detected at the function print()since colon (':'is missing before it file name and line number are printed so you know where to look in case the input came from script exceptions even if statement or expression is syntactically correctit may cause an error when an attempt is made to execute it errors detected during execution are called exceptions and are not unconditionally fatalyou will soon learn how to handle them in python programs most exceptions are not handled by programshoweverand result in error messages as shown here ( / traceback (most recent call last)file ""line in zerodivisionerrordivision by zero spam* traceback (most recent call last)file ""line in nameerrorname 'spamis not defined ' traceback (most recent call last)file ""line in typeerrorcan' convert 'intobject to str implicitly |
2,148 | the last line of the error message indicates what happened exceptions come in different typesand the type is printed as part of the messagethe types in the example are zerodivisionerrornameerror and typeerror the string printed as the exception type is the name of the built-in exception that occurred this is true for all built-in exceptionsbut need not be true for user-defined exceptions (although it is useful conventionstandard exception names are built-in identifiers (not reserved keywordsthe rest of the line provides detail based on the type of exception and what caused it the preceding part of the error message shows the context where the exception happenedin the form of stack traceback in general it contains stack traceback listing source lineshoweverit will not display lines read from standard input bltin-exceptions lists the built-in exceptions and their meanings handling exceptions it is possible to write programs that handle selected exceptions look at the following examplewhich asks the user for input until valid integer has been enteredbut allows the user to interrupt the program (using control- or whatever the operating system supports)note that user-generated interruption is signalled by raising the keyboardinterrupt exception while truetryx int(input("please enter number")break except valueerrorprint("oopsthat was no valid number try again "the try statement works as follows firstthe try clause (the statement(sbetween the try and except keywordsis executed if no exception occursthe except clause is skipped and execution of the try statement is finished if an exception occurs during execution of the try clausethe rest of the clause is skipped then if its type matches the exception named after the except keywordthe except clause is executedand then execution continues after the try statement if an exception occurs which does not match the exception named in the except clauseit is passed on to outer try statementsif no handler is foundit is an unhandled exception and execution stops with message as shown above try statement may have more than one except clauseto specify handlers for different exceptions at most one handler will be executed handlers only handle exceptions that occur in the corresponding try clausenot in other handlers of the same try statement an except clause may name multiple exceptions as parenthesized tuplefor exampleexcept (runtimeerrortypeerrornameerror)pass class in an except clause is compatible with an exception if it is the same class or base class thereof (but not the other way around -an except clause listing derived class is not compatible with base classfor examplethe following code will print bcd in that orderclass (exception)pass (continues on next page errors and exceptions |
2,149 | (continued from previous pageclass ( )pass class ( )pass for cls in [bcd]tryraise cls(except dprint(" "except cprint(" "except bprint(" "note that if the except clauses were reversed (with except first)it would have printed bbb -the first matching except clause is triggered the last except clause may omit the exception name( )to serve as wildcard use this with extreme cautionsince it is easy to mask real programming error in this wayit can also be used to print an error message and then re-raise the exception (allowing caller to handle the exception as well)import sys tryf open('myfile txt' readline( int( strip()except oserror as errprint("os error{ }format(err)except valueerrorprint("could not convert data to an integer "exceptprint("unexpected error:"sys exc_info()[ ]raise the try except statement has an optional else clausewhichwhen presentmust follow all except clauses it is useful for code that must be executed if the try clause does not raise an exception for examplefor arg in sys argv[ :]tryf open(arg' 'except oserrorprint('cannot open'argelseprint(arg'has'len( readlines())'lines' close(the use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn' raised by the code being protected by the try except statement when an exception occursit may have an associated valuealso known as the exception' argument the presence and type of the argument depend on the exception type the except clause may specify variable after the exception name the variable is bound to an exception instance with the arguments stored in instance args for conveniencethe exception instance defines __str__(so the arguments can be printed directly without having to reference args one may also handling exceptions |
2,150 | instantiate an exception first before raising it and add any attributes to it as desired tryraise exception('spam''eggs'except exception as instprint(type(inst)the exception instance print(inst argsarguments stored in args print(inst__str__ allows args to be printed directlybut may be overridden in exception subclasses xy inst args unpack args print(' ='xprint(' =' ('spam''eggs'('spam''eggs' spam eggs if an exception has argumentsthey are printed as the last part ('detail'of the message for unhandled exceptions exception handlers don' just handle exceptions if they occur immediately in the try clausebut also if they occur inside functions that are called (even indirectlyin the try clause for exampledef this_fails() / trythis_fails(except zerodivisionerror as errprint('handling run-time error:'errhandling run-time errordivision by zero raising exceptions the raise statement allows the programmer to force specified exception to occur for exampleraise nameerror('hithere'traceback (most recent call last)file ""line in nameerrorhithere the sole argument to raise indicates the exception to be raised this must be either an exception instance or an exception class ( class that derives from exceptionif an exception class is passedit will be implicitly instantiated by calling its constructor with no argumentsraise valueerror shorthand for 'raise valueerror()if you need to determine whether an exception was raised but don' intend to handle ita simpler form of the raise statement allows you to re-raise the exceptiontryraise nameerror('hithere'except nameerror(continues on next page errors and exceptions |
2,151 | (continued from previous pageprint('an exception flew by!'raise an exception flew bytraceback (most recent call last)file ""line in nameerrorhithere user-defined exceptions programs may name their own exceptions by creating new exception class (see classes for more about python classesexceptions should typically be derived from the exception classeither directly or indirectly exception classes can be defined which do anything any other class can dobut are usually kept simpleoften only offering number of attributes that allow information about the error to be extracted by handlers for the exception when creating module that can raise several distinct errorsa common practice is to create base class for exceptions defined by that moduleand subclass that to create specific exception classes for different error conditionsclass error(exception)"""base class for exceptions in this module ""pass class inputerror(error)"""exception raised for errors in the input attributesexpression -input expression in which the error occurred message -explanation of the error ""def __init__(selfexpressionmessage)self expression expression self message message class transitionerror(error)"""raised when an operation attempts state transition that' not allowed attributesprevious -state at beginning of transition next -attempted new state message -explanation of why the specific transition is not allowed ""def __init__(selfpreviousnextmessage)self previous previous self next next self message message most exceptions are defined with names that end in "error,similar to the naming of the standard exceptions many standard modules define their own exceptions to report errors that may occur in functions they define more information on classes is presented in classes user-defined exceptions |
2,152 | defining clean-up actions the try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances for exampletryraise keyboardinterrupt finallyprint('goodbyeworld!'goodbyeworldkeyboardinterrupt traceback (most recent call last)file ""line in finally clause is always executed before leaving the try statementwhether an exception has occurred or not when an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in an except or else clause)it is re-raised after the finally clause has been executed the finally clause is also executed "on the way outwhen any other clause of the try statement is left via breakcontinue or return statement more complicated exampledef divide(xy)tryresult except zerodivisionerrorprint("division by zero!"elseprint("result is"resultfinallyprint("executing finally clause"divide( result is executing finally clause divide( division by zeroexecuting finally clause divide(" "" "executing finally clause traceback (most recent call last)file ""line in file ""line in divide typeerrorunsupported operand type(sfor /'strand 'stras you can seethe finally clause is executed in any event the typeerror raised by dividing two strings is not handled by the except clause and therefore re-raised after the finally clause has been executed in real world applicationsthe finally clause is useful for releasing external resources (such as files or network connections)regardless of whether the use of the resource was successful predefined clean-up actions some objects define standard clean-up actions to be undertaken when the object is no longer neededregardless of whether or not the operation using the object succeeded or failed look at the following examplewhich tries to open file and print its contents to the screen errors and exceptions |
2,153 | for line in open("myfile txt")print(lineend=""the problem with this code is that it leaves the file open for an indeterminate amount of time after this part of the code has finished executing this is not an issue in simple scriptsbut can be problem for larger applications the with statement allows objects like files to be used in way that ensures they are always cleaned up promptly and correctly with open("myfile txt"as ffor line in fprint(lineend=""after the statement is executedthe file is always closedeven if problem was encountered while processing the lines objects whichlike filesprovide predefined clean-up actions will indicate this in their documentation predefined clean-up actions |
2,154 | errors and exceptions |
2,155 | nine classes classes provide means of bundling data and functionality together creating new class creates new type of objectallowing new instances of that type to be made each class instance can have attributes attached to it for maintaining its state class instances can also have methods (defined by its classfor modifying its state compared with other programming languagespython' class mechanism adds classes with minimum of new syntax and semantics it is mixture of the class mechanisms found in +and modula- python classes provide all the standard features of object oriented programmingthe class inheritance mechanism allows multiple base classesa derived class can override any methods of its base class or classesand method can call the method of base class with the same name objects can contain arbitrary amounts and kinds of data as is true for modulesclasses partake of the dynamic nature of pythonthey are created at runtimeand can be modified further after creation in +terminologynormally class members (including the data membersare public (except see below private variables)and all member functions are virtual as in modula- there are no shorthands for referencing the object' members from its methodsthe method function is declared with an explicit first argument representing the objectwhich is provided implicitly by the call as in smalltalkclasses themselves are objects this provides semantics for importing and renaming unlike +and modula- built-in types can be used as base classes for extension by the user alsolike in ++most built-in operators with special syntax (arithmetic operatorssubscripting etc can be redefined for class instances (lacking universally accepted terminology to talk about classesi will make occasional use of smalltalk and +terms would use modula- termssince its object-oriented semantics are closer to those of python than ++but expect that few readers have heard of it word about names and objects objects have individualityand multiple names (in multiple scopescan be bound to the same object this is known as aliasing in other languages this is usually not appreciated on first glance at pythonand can be safely ignored when dealing with immutable basic types (numbersstringstupleshoweveraliasing has possibly surprising effect on the semantics of python code involving mutable objects such as listsdictionariesand most other types this is usually used to the benefit of the programsince aliases behave like pointers in some respects for examplepassing an object is cheap since only pointer is passed by the implementationand if function modifies an object passed as an argumentthe caller will see the change -this eliminates the need for two different argument passing mechanisms as in pascal python scopes and namespaces before introducing classesi first have to tell you something about python' scope rules class definitions play some neat tricks with namespacesand you need to know how scopes and namespaces work to fully |
2,156 | understand what' going on incidentallyknowledge about this subject is useful for any advanced python programmer let' begin with some definitions namespace is mapping from names to objects most namespaces are currently implemented as python dictionariesbut that' normally not noticeable in any way (except for performance)and it may change in the future examples of namespaces arethe set of built-in names (containing functions such as abs()and built-in exception names)the global names in moduleand the local names in function invocation in sense the set of attributes of an object also form namespace the important thing to know about namespaces is that there is absolutely no relation between names in different namespacesfor instancetwo different modules may both define function maximize without confusion -users of the modules must prefix it with the module name by the wayi use the word attribute for any name following dot -for examplein the expression realreal is an attribute of the object strictly speakingreferences to names in modules are attribute referencesin the expression modname funcnamemodname is module object and funcname is an attribute of it in this case there happens to be straightforward mapping between the module' attributes and the global names defined in the modulethey share the same namespace! attributes may be read-only or writable in the latter caseassignment to attributes is possible module attributes are writableyou can write modname the_answer writable attributes may also be deleted with the del statement for exampledel modname the_answer will remove the attribute the_answer from the object named by modname namespaces are created at different moments and have different lifetimes the namespace containing the built-in names is created when the python interpreter starts upand is never deleted the global namespace for module is created when the module definition is read innormallymodule namespaces also last until the interpreter quits the statements executed by the top-level invocation of the interpretereither read from script file or interactivelyare considered part of module called __main__so they have their own global namespace (the built-in names actually also live in modulethis is called builtins the local namespace for function is created when the function is calledand deleted when the function returns or raises an exception that is not handled within the function (actuallyforgetting would be better way to describe what actually happens of courserecursive invocations each have their own local namespace scope is textual region of python program where namespace is directly accessible "directly accessiblehere means that an unqualified reference to name attempts to find the name in the namespace although scopes are determined staticallythey are used dynamically at any time during executionthere are at least three nested scopes whose namespaces are directly accessiblethe innermost scopewhich is searched firstcontains the local names the scopes of any enclosing functionswhich are searched starting with the nearest enclosing scopecontains non-localbut also non-global names the next-to-last scope contains the current module' global names the outermost scope (searched lastis the namespace containing built-in names if name is declared globalthen all references and assignments go directly to the middle scope containing the module' global names to rebind variables found outside of the innermost scopethe nonlocal statement can be usedif not declared nonlocalthose variables are read-only (an attempt to write to such variable will simply create new local variable in the innermost scopeleaving the identically named outer variable unchanged except for one thing module objects have secret read-only attribute called __dict__ which returns the dictionary used to implement the module' namespacethe name __dict__ is an attribute but not global name obviouslyusing this violates the abstraction of namespace implementationand should be restricted to things like post-mortem debuggers classes |
2,157 | usuallythe local scope references the local names of the (textuallycurrent function outside functionsthe local scope references the same namespace as the global scopethe module' namespace class definitions place yet another namespace in the local scope it is important to realize that scopes are determined textuallythe global scope of function defined in module is that module' namespaceno matter from where or by what alias the function is called on the other handthe actual search for names is done dynamicallyat run time -howeverthe language definition is evolving towards static name resolutionat "compiletimeso don' rely on dynamic name resolution(in factlocal variables are already determined statically special quirk of python is that if no global statement is in effect assignments to names always go into the innermost scope assignments do not copy data -they just bind names to objects the same is true for deletionsthe statement del removes the binding of from the namespace referenced by the local scope in factall operations that introduce new names use the local scopein particularimport statements and function definitions bind the module or function name in the local scope the global statement can be used to indicate that particular variables live in the global scope and should be rebound therethe nonlocal statement indicates that particular variables live in an enclosing scope and should be rebound there scopes and namespaces example this is an example demonstrating how to reference the different scopes and namespacesand how global and nonlocal affect variable bindingdef scope_test()def do_local()spam "local spamdef do_nonlocal()nonlocal spam spam "nonlocal spamdef do_global()global spam spam "global spamspam "test spamdo_local(print("after local assignment:"spamdo_nonlocal(print("after nonlocal assignment:"spamdo_global(print("after global assignment:"spamscope_test(print("in global scope:"spamthe output of the example code isafter local assignmenttest spam after nonlocal assignmentnonlocal spam after global assignmentnonlocal spam in global scopeglobal spam note how the local assignment (which is defaultdidn' change scope_test' binding of spam the nonlocal assignment changed scope_test' binding of spamand the global assignment changed the module-level binding python scopes and namespaces |
2,158 | you can also see that there was no previous binding for spam before the global assignment first look at classes classes introduce little bit of new syntaxthree new object typesand some new semantics class definition syntax the simplest form of class definition looks like thisclass classnameclass definitionslike function definitions (def statementsmust be executed before they have any effect (you could conceivably place class definition in branch of an if statementor inside function in practicethe statements inside class definition will usually be function definitionsbut other statements are allowedand sometimes useful -we'll come back to this later the function definitions inside class normally have peculiar form of argument listdictated by the calling conventions for methods -againthis is explained later when class definition is entereda new namespace is createdand used as the local scope -thusall assignments to local variables go into this new namespace in particularfunction definitions bind the name of the new function here when class definition is left normally (via the end) class object is created this is basically wrapper around the contents of the namespace created by the class definitionwe'll learn more about class objects in the next section the original local scope (the one in effect just before the class definition was enteredis reinstatedand the class object is bound here to the class name given in the class definition header (classname in the exampleclass objects class objects support two kinds of operationsattribute references and instantiation attribute references use the standard syntax used for all attribute references in pythonobj name valid attribute names are all the names that were in the class' namespace when the class object was created soif the class definition looked like thisclass myclass""" simple example class"" def (self)return 'hello worldthen myclass and myclass are valid attribute referencesreturning an integer and function objectrespectively class attributes can also be assigned toso you can change the value of myclass by assignment __doc__ is also valid attributereturning the docstring belonging to the class" simple example class classes |
2,159 | class instantiation uses function notation just pretend that the class object is parameterless function that returns new instance of the class for example (assuming the above class) myclass(creates new instance of the class and assigns this object to the local variable the instantiation operation ("callinga class objectcreates an empty object many classes like to create objects with instances customized to specific initial state therefore class may define special method named __init__()like thisdef __init__(self)self data [when class defines an __init__(methodclass instantiation automatically invokes __init__(for the newly-created class instance so in this examplea newinitialized instance can be obtained byx myclass(of coursethe __init__(method may have arguments for greater flexibility in that casearguments given to the class instantiation operator are passed on to __init__(for exampleclass complexdef __init__(selfrealpartimagpart)self realpart self imagpart complex( - rx ( - instance objects now what can we do with instance objectsthe only operations understood by instance objects are attribute references there are two kinds of valid attribute namesdata attributes and methods data attributes correspond to "instance variablesin smalltalkand to "data membersin +data attributes need not be declaredlike local variablesthey spring into existence when they are first assigned to for exampleif is the instance of myclass created abovethe following piece of code will print the value without leaving tracex counter while counter counter counter print( counterdel counter the other kind of instance attribute reference is method method is function that "belongs toan object (in pythonthe term method is not unique to class instancesother object types can have methods as well for examplelist objects have methods called appendinsertremovesortand so on howeverin the following discussionwe'll use the term method exclusively to mean methods of class instance objectsunless explicitly stated otherwise valid method names of an instance object depend on its class by definitionall attributes of class that are function objects define corresponding methods of its instances so in our examplex is valid method referencesince myclass is functionbut is notsince myclass is not but is not the same thing as myclass -it is method objectnot function object first look at classes |
2,160 | method objects usuallya method is called right after it is boundx (in the myclass examplethis will return the string 'hello worldhoweverit is not necessary to call method right awayx is method objectand can be stored away and called at later time for examplexf while trueprint(xf()will continue to print hello world until the end of time what exactly happens when method is calledyou may have noticed that (was called without an argument aboveeven though the function definition for (specified an argument what happened to the argumentsurely python raises an exception when function that requires an argument is called without any -even if the argument isn' actually used actuallyyou may have guessed the answerthe special thing about methods is that the instance object is passed as the first argument of the function in our examplethe call (is exactly equivalent to myclass (xin generalcalling method with list of arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method' instance object before the first argument if you still don' understand how methods worka look at the implementation can perhaps clarify matters when non-data attribute of an instance is referencedthe instance' class is searched if the name denotes valid class attribute that is function objecta method object is created by packing (pointers tothe instance object and the function object just found together in an abstract objectthis is the method object when the method object is called with an argument lista new argument list is constructed from the instance object and the argument listand the function object is called with this new argument list class and instance variables generally speakinginstance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the classclass dogkind 'canineclass variable shared by all instances def __init__(selfname)self name name instance variable unique to each instance dog('fido' dog('buddy' kind 'caninee kind 'canined name 'fidoe name 'buddy shared by all dogs shared by all dogs unique to unique to classes |
2,161 | as discussed in word about names and objectsshared data can have possibly surprising effects with involving mutable objects such as lists and dictionaries for examplethe tricks list in the following code should not be used as class variable because just single list would be shared by all dog instancesclass dogtricks [mistaken use of class variable def __init__(selfname)self name name def add_trick(selftrick)self tricks append(trickd dog('fido' dog('buddy' add_trick('roll over' add_trick('play dead' tricks unexpectedly shared by all dogs ['roll over''play dead'correct design of the class should use an instance variable insteadclass dogdef __init__(selfname)self name name self tricks [creates new empty list for each dog def add_trick(selftrick)self tricks append(trickd dog('fido' dog('buddy' add_trick('roll over' add_trick('play dead' tricks ['roll over' tricks ['play dead' random remarks data attributes override method attributes with the same nameto avoid accidental name conflictswhich may cause hard-to-find bugs in large programsit is wise to use some kind of convention that minimizes the chance of conflicts possible conventions include capitalizing method namesprefixing data attribute names with small unique string (perhaps just an underscore)or using verbs for methods and nouns for data attributes data attributes may be referenced by methods as well as by ordinary users ("clients"of an object in other wordsclasses are not usable to implement pure abstract data types in factnothing in python makes it possible to enforce data hiding -it is all based upon convention (on the other handthe python implementationwritten in ccan completely hide implementation details and control access to an object if necessarythis can be used by extensions to python written in clients should use data attributes with care -clients may mess up invariants maintained by the methods random remarks |
2,162 | by stamping on their data attributes note that clients may add data attributes of their own to an instance object without affecting the validity of the methodsas long as name conflicts are avoided -againa naming convention can save lot of headaches here there is no shorthand for referencing data attributes (or other methods!from within methods find that this actually increases the readability of methodsthere is no chance of confusing local variables and instance variables when glancing through method oftenthe first argument of method is called self this is nothing more than conventionthe name self has absolutely no special meaning to python notehoweverthat by not following the convention your code may be less readable to other python programmersand it is also conceivable that class browser program might be written that relies upon such convention any function object that is class attribute defines method for instances of that class it is not necessary that the function definition is textually enclosed in the class definitionassigning function object to local variable in the class is also ok for examplefunction defined outside the class def (selfxy)return min(xx+yclass cf def (self)return 'hello worldh now fg and are all attributes of class that refer to function objectsand consequently they are all methods of instances of - being exactly equivalent to note that this practice usually only serves to confuse the reader of program methods may call other methods by using method attributes of the self argumentclass bagdef __init__(self)self data [def add(selfx)self data append(xdef addtwice(selfx)self add(xself add(xmethods may reference global names in the same way as ordinary functions the global scope associated with method is the module containing its definition ( class is never used as global scope while one rarely encounters good reason for using global data in methodthere are many legitimate uses of the global scopefor one thingfunctions and modules imported into the global scope can be used by methodsas well as functions and classes defined in it usuallythe class containing the method is itself defined in this global scopeand in the next section we'll find some good reasons why method would want to reference its own class each value is an objectand therefore has class (also called its typeit is stored as object __class__ classes |
2,163 | inheritance of coursea language feature would not be worthy of the name "classwithout supporting inheritance the syntax for derived class definition looks like thisclass derivedclassname(baseclassname)the name baseclassname must be defined in scope containing the derived class definition in place of base class nameother arbitrary expressions are also allowed this can be usefulfor examplewhen the base class is defined in another moduleclass derivedclassname(modname baseclassname)execution of derived class definition proceeds the same as for base class when the class object is constructedthe base class is remembered this is used for resolving attribute referencesif requested attribute is not found in the classthe search proceeds to look in the base class this rule is applied recursively if the base class itself is derived from some other class there' nothing special about instantiation of derived classesderivedclassname(creates new instance of the class method references are resolved as followsthe corresponding class attribute is searcheddescending down the chain of base classes if necessaryand the method reference is valid if this yields function object derived classes may override methods of their base classes because methods have no special privileges when calling other methods of the same objecta method of base class that calls another method defined in the same base class may end up calling method of derived class that overrides it (for +programmersall methods in python are effectively virtual an overriding method in derived class may in fact want to extend rather than simply replace the base class method of the same name there is simple way to call the base class method directlyjust call baseclassname methodname(selfargumentsthis is occasionally useful to clients as well (note that this only works if the base class is accessible as baseclassname in the global scope python has two built-in functions that work with inheritanceuse isinstance(to check an instance' typeisinstance(objintwill be true only if obj __class__ is int or some class derived from int use issubclass(to check class inheritanceissubclass(boolintis true since bool is subclass of int howeverissubclass(floatintis false since float is not subclass of int multiple inheritance python supports form of multiple inheritance as well class definition with multiple base classes looks like thisclass derivedclassname(base base base ) inheritance |
2,164 | for most purposesin the simplest casesyou can think of the search for attributes inherited from parent class as depth-firstleft-to-rightnot searching twice in the same class where there is an overlap in the hierarchy thusif an attribute is not found in derivedclassnameit is searched for in base then (recursivelyin the base classes of base and if it was not found thereit was searched for in base and so on in factit is slightly more complex than thatthe method resolution order changes dynamically to support cooperative calls to super(this approach is known in some other multiple-inheritance languages as call-next-method and is more powerful than the super call found in single-inheritance languages dynamic ordering is necessary because all cases of multiple inheritance exhibit one or more diamond relationships (where at least one of the parent classes can be accessed through multiple paths from the bottommost classfor exampleall classes inherit from objectso any case of multiple inheritance provides more than one path to reach object to keep the base classes from being accessed more than oncethe dynamic algorithm linearizes the search order in way that preserves the left-to-right ordering specified in each classthat calls each parent only onceand that is monotonic (meaning that class can be subclassed without affecting the precedence order of its parentstaken togetherthese properties make it possible to design reliable and extensible classes with multiple inheritance for more detailsee private variables "privateinstance variables that cannot be accessed except from inside an object don' exist in python howeverthere is convention that is followed by most python codea name prefixed with an underscore ( _spamshould be treated as non-public part of the api (whether it is functiona method or data memberit should be considered an implementation detail and subject to change without notice since there is valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses)there is limited support for such mechanismcalled name mangling any identifier of the form __spam (at least two leading underscoresat most one trailing underscoreis textually replaced with _classname__spamwhere classname is the current class name with leading underscore(sstripped this mangling is done without regard to the syntactic position of the identifieras long as it occurs within the definition of class name mangling is helpful for letting subclasses override methods without breaking intraclass method calls for exampleclass mappingdef __init__(selfiterable)self items_list [self __update(iterabledef update(selfiterable)for item in iterableself items_list append(item__update update private copy of original update(method class mappingsubclass(mapping)def update(selfkeysvalues)provides new signature for update(but does not break __init__(for item in zip(keysvalues)self items_list append(itemnote that the mangling rules are designed mostly to avoid accidentsit still is possible to access or modify variable that is considered private this can even be useful in special circumstancessuch as in the debugger classes |
2,165 | notice that code passed to exec(or eval(does not consider the classname of the invoking class to be the current classthis is similar to the effect of the global statementthe effect of which is likewise restricted to code that is byte-compiled together the same restriction applies to getattr()setattr(and delattr()as well as when referencing __dict__ directly odds and ends sometimes it is useful to have data type similar to the pascal "recordor "struct"bundling together few named data items an empty class definition will do nicelyclass employeepass john employee(create an empty employee record fill the fields of the record john name 'john doejohn dept 'computer labjohn salary piece of python code that expects particular abstract data type can often be passed class that emulates the methods of that data type instead for instanceif you have function that formats some data from file objectyou can define class with methods read(and readline(that get the data from string buffer insteadand pass it as an argument instance method objects have attributestoom __self__ is the instance object with the method ()and __func__ is the function object corresponding to the method iterators by now you have probably noticed that most container objects can be looped over using for statementfor element in [ ]print(elementfor element in ( )print(elementfor key in {'one': 'two': }print(keyfor char in " "print(charfor line in open("myfile txt")print(lineend=''this style of access is clearconciseand convenient the use of iterators pervades and unifies python behind the scenesthe for statement calls iter(on the container object the function returns an iterator object that defines the method __next__(which accesses elements in the container one at time when there are no more elements__next__(raises stopiteration exception which tells the for loop to terminate you can call the __next__(method using the next(built-in functionthis example shows how it all workss 'abcit iter(sit (continues on next page odds and ends |
2,166 | (continued from previous pagenext(it'anext(it'bnext(it'cnext(ittraceback (most recent call last)file ""line in next(itstopiteration having seen the mechanics behind the iterator protocolit is easy to add iterator behavior to your classes define an __iter__(method which returns an object with __next__(method if the class defines __next__()then __iter__(can just return selfclass reverse"""iterator for looping over sequence backwards ""def __init__(selfdata)self data data self index len(datadef __iter__(self)return self def __next__(self)if self index = raise stopiteration self index self index return self data[self indexrev reverse('spam'iter(revfor char in revprint(charm generators generators are simple and powerful tool for creating iterators they are written like regular functions but use the yield statement whenever they want to return data each time next(is called on itthe generator resumes where it left off (it remembers all the data values and which statement was last executedan example shows that generators can be trivially easy to createdef reverse(data)for index in range(len(data)- - - )yield data[index classes |
2,167 | for char in reverse('golf')print(charf anything that can be done with generators can also be done with class-based iterators as described in the previous section what makes generators so compact is that the __iter__(and __next__(methods are created automatically another key feature is that the local variables and execution state are automatically saved between calls this made the function easier to write and much more clear than an approach using instance variables like self index and self data in addition to automatic method creation and saving program statewhen generators terminatethey automatically raise stopiteration in combinationthese features make it easy to create iterators with no more effort than writing regular function generator expressions some simple generators can be coded succinctly as expressions using syntax similar to list comprehensions but with parentheses instead of square brackets these expressions are designed for situations where the generator is used right away by an enclosing function generator expressions are more compact but less versatile than full generator definitions and tend to be more memory friendly than equivalent list comprehensions examplessum( * for in range( ) xvec [ yvec [ sum( * for , in zip(xvecyvec) sum of squares dot product from math import pisin sine_table {xsin( *pi/ for in range( )unique_words set(word for line in page for word in line split()valedictorian max((student gpastudent namefor student in graduatesdata 'golflist(data[ifor in range(len(data)- - - )[' '' '' '' ' generator expressions |
2,168 | classes |
2,169 | ten brief tour of the standard library operating system interface the os module provides dozens of functions for interacting with the operating systemimport os os getcwd(return the current working directory ' :\\python os chdir('/server/accesslogs'change current working directory os system('mkdir today'run the command mkdir in the system shell be sure to use the import os style instead of from os import this will keep os open(from shadowing the built-in open(function which operates much differently the built-in dir(and help(functions are useful as interactive aids for working with large modules like osimport os dir(oshelp(osfor daily file and directory management tasksthe shutil module provides higher level interface that is easier to useimport shutil shutil copyfile('data db''archive db''archive dbshutil move('/build/executables''installdir''installdir file wildcards the glob module provides function for making file lists from directory wildcard searchesimport glob glob glob('py'['primes py''random py''quote py' |
2,170 | command line arguments common utility scripts often need to process command line arguments these arguments are stored in the sys module' argv attribute as list for instance the following output results from running python demo py one two three at the command lineimport sys print(sys argv['demo py''one''two''three'the getopt module processes sys argv using the conventions of the unix getopt(function more powerful and flexible command line processing is provided by the argparse module error output redirection and program termination the sys module also has attributes for stdinstdoutand stderr the latter is useful for emitting warnings and error messages to make them visible even when stdout has been redirectedsys stderr write('warninglog file not found starting new one\ 'warninglog file not found starting new one the most direct way to terminate script is to use sys exit( string pattern matching the re module provides regular expression tools for advanced string processing for complex matching and manipulationregular expressions offer succinctoptimized solutionsimport re re findall( '\bf[ - ]*''which foot or hand fell fastest'['foot''fell''fastest're sub( '(\ [ - ]+\ ' '\ ''cat in the the hat''cat in the hatwhen only simple capabilities are neededstring methods are preferred because they are easier to read and debug'tea for tooreplace('too''two''tea for two mathematics the math module gives access to the underlying library functions for floating point mathimport math math cos(math pi math log( the random module provides tools for making random selections brief tour of the standard library |
2,171 | import random random choice(['apple''pear''banana']'applerandom sample(range( ) sampling without replacement [ random random(random float random randrange( random integer chosen from range( the statistics module calculates basic statistical properties (the meanmedianvarianceetc of numeric dataimport statistics data [ statistics mean(data statistics median(data statistics variance(data the scipy project < internet access there are number of modules for accessing the internet and processing internet protocols two of the simplest are urllib request for retrieving data from urls and smtplib for sending mailfrom urllib request import urlopen with urlopen(for line in responseline line decode('utf- 'decoding the binary data to text if 'estin line or 'edtin linelook for eastern time print(linenov : : pm est import smtplib server smtplib smtp('localhost'server sendmail('soothsayer@example org''jcaesar@example org'"""tojcaesar@example org fromsoothsayer@example org beware the ides of march """server quit((note that the second example needs mailserver running on localhost dates and times the datetime module supplies classes for manipulating dates and times in both simple and complex ways while date and time arithmetic is supportedthe focus of the implementation is on efficient member extrac internet access |
2,172 | tion for output formatting and manipulation the module also supports objects that are timezone aware dates are easily constructed and formatted from datetime import date now date today(now datetime date( now strftime("% -% -% % % % is % on the % day of % " dec is tuesday on the day of december dates support calendar arithmetic birthday date( age now birthday age days data compression common data archiving and compression formats are directly supported by modules includingzlibgzipbz lzmazipfile and tarfile import zlib 'witch which has which witches wrist watchlen( zlib compress(slen( zlib decompress(tb'witch which has which witches wrist watchzlib crc ( performance measurement some python users develop deep interest in knowing the relative performance of different approaches to the same problem python provides measurement tool that answers those questions immediately for exampleit may be tempting to use the tuple packing and unpacking feature instead of the traditional approach to swapping arguments the timeit module quickly demonstrates modest performance advantagefrom timeit import timer timer(' =aa=bb= '' = = 'timeit( timer(' , , '' = = 'timeit( in contrast to timeit' fine level of granularitythe profile and pstats modules provide tools for identifying time critical sections in larger blocks of code brief tour of the standard library |
2,173 | quality control one approach for developing high quality software is to write tests for each function as it is developed and to run those tests frequently during the development process the doctest module provides tool for scanning module and validating tests embedded in program' docstrings test construction is as simple as cutting-and-pasting typical call along with its results into the docstring this improves the documentation by providing the user with an example and it allows the doctest module to make sure the code remains true to the documentationdef average(values)"""computes the arithmetic mean of list of numbers print(average([ ]) ""return sum(valueslen(valuesimport doctest doctest testmod(automatically validate the embedded tests the unittest module is not as effortless as the doctest modulebut it allows more comprehensive set of tests to be maintained in separate fileimport unittest class teststatisticalfunctions(unittest testcase)def test_average(self)self assertequal(average([ ]) self assertequal(round(average([ ]) ) with self assertraises(zerodivisionerror)average([]with self assertraises(typeerror)average( unittest main(calling from the command line invokes all tests batteries included python has "batteries includedphilosophy this is best seen through the sophisticated and robust capabilities of its larger packages for examplethe xmlrpc client and xmlrpc server modules make implementing remote procedure calls into an almost trivial task despite the modules namesno direct knowledge or handling of xml is needed the email package is library for managing email messagesincluding mime and other rfc based message documents unlike smtplib and poplib which actually send and receive messagesthe email package has complete toolset for building or decoding complex message structures (including attachmentsand for implementing internet encoding and header protocols the json package provides robust support for parsing this popular data interchange format the csv module supports direct reading and writing of files in comma-separated value formatcommonly supported by databases and spreadsheets xml processing is supported by the xml etree elementtreexml dom and xml sax packages togetherthese modules and packages greatly simplify data interchange between python applications and other tools quality control |
2,174 | the sqlite module is wrapper for the sqlite database libraryproviding persistent database that can be updated and accessed using slightly nonstandard sql syntax internationalization is supported by number of modules including gettextlocaleand the codecs package brief tour of the standard library |
2,175 | eleven brief tour of the standard library -part ii this second tour covers more advanced modules that support professional programming needs these modules rarely occur in small scripts output formatting the reprlib module provides version of repr(customized for abbreviated displays of large or deeply nested containersimport reprlib reprlib repr(set('supercalifragilisticexpialidocious')"{' '' '' '' '' '' '}the pprint module offers more sophisticated control over printing both built-in and user defined objects in way that is readable by the interpreter when the result is longer than one linethe "pretty printeradds line breaks and indentation to more clearly reveal data structureimport pprint [[[['black''cyan']'white'['green''red']][['magenta''yellow']'blue']]pprint pprint(twidth= [[[['black''cyan']'white'['green''red']][['magenta''yellow']'blue']]the textwrap module formats paragraphs of text to fit given screen widthimport textwrap doc """the wrap(method is just like fill(except that it returns list of strings instead of one big string with newlines to separate the wrapped lines ""print(textwrap fill(docwidth= )the wrap(method is just like fill(except that it returns list of strings instead of one big string with newlines to separate the wrapped lines the locale module accesses database of culture specific data formats the grouping attribute of locale' format function provides direct way of formatting numbers with group separators |
2,176 | import locale locale setlocale(locale lc_all'english_united states ''english_united states conv locale localeconv(get mapping of conventions locale format("% "xgrouping=true' , , locale format_string("% * "(conv['currency_symbol']conv['frac_digits'] )grouping=true'$ , , templating the string module includes versatile template class with 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 underscoressurrounding the placeholder with braces allows it to be followed by more alphanumeric letters with no intervening spaces writing $creates single escaped $from string import template template('${village}folk send $$ to $cause ' substitute(village='nottingham'cause='the ditch fund''nottinghamfolk send $ to the ditch fund the substitute(method raises keyerror when placeholder is not supplied in dictionary or keyword argument for mail-merge style applicationsuser supplied data may be incomplete and the safe_substitute(method may be more appropriate -it will leave placeholders unchanged if data is missingt template('return the $item to $owner ' dict(item='unladen swallow' substitute(dtraceback (most recent call last)keyerror'ownert safe_substitute( 'return the unladen swallow to $owner template subclasses can specify custom delimiter for examplea batch renaming utility for photo browser may elect to use percent signs for placeholders such as the current dateimage sequence numberor file formatimport timeos path photofiles ['img_ jpg''img_ jpg''img_ jpg'class batchrename(template)delimiter '%fmt input('enter rename style (% -date % -seqnum % -format)enter rename style (% -date % -seqnum % -format)ashley_% % ' batchrename(fmtdate time strftime('% % % 'for ifilename in enumerate(photofiles)baseext os path splitext(filenamenewname substitute( =daten=if=ext(continues on next page brief tour of the standard library -part ii |
2,177 | (continued from previous pageprint('{ --{ }format(filenamenewname)img_ jpg --ashley_ jpg img_ jpg --ashley_ jpg img_ jpg --ashley_ jpg another application for templating is separating program logic from the details of multiple output formats this makes it possible to substitute custom templates for xml filesplain text reportsand html web reports working with binary data record layouts the struct module provides pack(and unpack(functions for working with variable length binary record formats the following example shows how to loop through header information in zip file without using the zipfile module pack codes "hand "irepresent two and four byte unsigned numbers respectively the "<indicates that they are standard size and in little-endian byte orderimport struct with open('myfile zip''rb'as fdata read(start for in range( )show the first file headers start + fields struct unpack('<iiihh'data[start:start+ ]crc comp_sizeuncomp_sizefilenamesizeextra_size fields start + filename data[start:start+filenamesizestart +filenamesize extra data[start:start+extra_sizeprint(filenamehex(crc )comp_sizeuncomp_sizestart +extra_size comp_size skip to the next header multi-threading threading is technique for decoupling tasks which are not sequentially dependent threads can be used to improve the responsiveness of applications that accept user input while other tasks run in the background related use case is running / in parallel with computations in another thread the following code shows how the high level threading module can run tasks in background while the main program continues to runimport threadingzipfile class asynczip(threading thread)def __init__(selfinfileoutfile)threading thread __init__(selfself infile infile self outfile outfile (continues on next page working with binary data record layouts |
2,178 | (continued from previous pagedef run(self) zipfile zipfile(self outfile' 'zipfile zip_deflatedf write(self infilef close(print('finished background zip of:'self infilebackground asynczip('mydata txt''myarchive zip'background start(print('the main program continues to run in foreground 'background join(wait for the background task to finish print('main program waited until background was done 'the principal challenge of multi-threaded applications is coordinating threads that share data or other resources to that endthe threading module provides number of synchronization primitives including lockseventscondition variablesand semaphores while those tools are powerfulminor design errors can result in problems that are difficult to reproduce sothe preferred approach to task coordination is to concentrate all access to resource in single thread and then use the queue module to feed that thread with requests from other threads applications using queue objects for inter-thread communication and coordination are easier to designmore readableand more reliable logging the logging module offers full featured and flexible logging system at its simplestlog messages are sent to file or to sys stderrimport logging logging debug('debugging information'logging info('informational message'logging warning('warning:config file % not found''server conf'logging error('error occurred'logging critical('critical error -shutting down'this produces the following outputwarning:root:warning:config file server conf not found error:root:error occurred critical:root:critical error -shutting down by defaultinformational and debugging messages are suppressed and the output is sent to standard error other output options include routing messages through emaildatagramssocketsor to an http server new filters can select different routing based on message prioritydebuginfowarningerrorand critical the logging system can be configured directly from python or can be loaded from user editable configuration file for customized logging without altering the application brief tour of the standard library -part ii |
2,179 | weak references python does automatic memory management (reference counting for most objects and garbage collection to eliminate cyclesthe memory is freed shortly after the last reference to it has been eliminated this approach works fine for most applications but occasionally there is need to track objects only as long as they are being used by something else unfortunatelyjust tracking them creates reference that makes them permanent the weakref module provides tools for tracking objects without creating reference when the object is no longer neededit is automatically removed from weakref table and callback is triggered for weakref objects typical applications include caching objects that are expensive to createimport weakrefgc class adef __init__(selfvalue)self value value def __repr__(self)return str(self valuea ( create reference weakref weakvaluedictionary( ['primary' does not create reference ['primary'fetch the object if it is still alive del remove the one reference gc collect(run garbage collection right away ['primary'entry was automatically removed traceback (most recent call last)file ""line in ['primary'entry was automatically removed file " :/python /lib/weakref py"line in __getitem__ self data[key](keyerror'primary tools for working with lists many data structure needs can be met with the built-in list type howeversometimes there is need for alternative implementations with different performance trade-offs the array module provides an array(object that is like 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 " "rather than the usual bytes per entry for regular lists of python int objectsfrom array import array array(' '[ ]sum( [ : array(' '[ ]the collections module provides deque(object that is like 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 weak references |
2,180 | from collections import deque deque(["task ""task ""task "] append("task "print("handling" popleft()handling task unsearched deque([starting_node]def breadth_first_search(unsearched)node unsearched popleft(for in gen_moves(node)if is_goal( )return unsearched append(min addition to alternative list implementationsthe library also offers other tools such as the bisect module with functions for manipulating sorted listsimport bisect scores [( 'perl')( 'tcl')( 'lua')( 'python')bisect insort(scores( 'ruby')scores [( 'perl')( 'tcl')( 'ruby')( 'lua')( 'python')the heapq module provides functions for implementing heaps based on regular lists the lowest valued entry is always kept at position zero this is useful for applications which repeatedly access the smallest element but do not want to run full list sortfrom heapq import heapifyheappopheappush data [ heapify(datarearrange the list into heap order heappush(data- add new entry [heappop(datafor in range( )fetch the three smallest entries [- decimal floating point arithmetic the decimal module offers decimal datatype for decimal floating point arithmetic compared to the built-in float implementation of binary floating pointthe class is especially helpful for financial applications and other uses which require exact decimal representationcontrol over precisioncontrol over rounding to meet legal or regulatory requirementstracking of significant decimal placesor applications where the user expects the results to match calculations done by hand for examplecalculating tax on cent phone charge gives different results in decimal floating point and binary floating point the difference becomes significant if the results are rounded to the nearest centfrom decimal import round(decimal(' 'decimal(' ') decimal(' 'round brief tour of the standard library -part ii |
2,181 | the decimal result keeps trailing zeroautomatically 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 decimal class to perform modulo calculations and equality tests that are unsuitable for binary floating pointdecimal(' 'decimal( 'decimal(' ' sum([decimal(' ')]* =decimal(' 'true sum([ ]* = false the decimal module provides arithmetic with as much precision as neededgetcontext(prec decimal( decimal( decimal(' ' decimal floating point arithmetic |
2,182 | brief tour of the standard library -part ii |
2,183 | twelve virtual environments and packages introduction python applications will often use packages and modules that don' come as part of the standard library applications will sometimes need specific version of librarybecause the application may require that particular bug has been fixed or the application may be written using an obsolete version of the library' interface this means it may not be possible for one python installation to meet the requirements of every application if application needs version of particular module but application needs version then the requirements are in conflict and installing either version or will leave one application unable to run the solution for this problem is to create virtual environmenta self-contained directory tree that contains python installation for particular version of pythonplus number of additional packages different applications can then use different virtual environments to resolve the earlier example of conflicting requirementsapplication can have its own virtual environment with version installed while application has another virtual environment with version if application requires library be upgraded to version this will not affect application ' environment creating virtual environments the module used to create and manage virtual environments is called venv venv will usually install the most recent version of python that you have available if you have multiple versions of python on your systemyou can select specific python version by running python or whichever version you want to create virtual environmentdecide upon directory where you want to place itand run the venv module as script with the directory pathpython - venv tutorial-env this will create the tutorial-env directory if it doesn' existand also create directories inside it containing copy of the python interpreterthe standard libraryand various supporting files once you've created virtual environmentyou may activate it on windowsruntutorial-env\scripts\activate bat on unix or macosrunsource tutorial-env/bin/activate |
2,184 | (this script is written for the bash shell if you use the csh or fish shellsthere are alternate activate csh and activate fish scripts you should use instead activating the virtual environment will change your shell' prompt to show what virtual environment you're usingand modify the environment so that running python will get you that particular version and installation of python for examplesource ~/envs/tutorial-env/bin/activate (tutorial-envpython python (defaultmay : : import sys sys path ['''/usr/local/lib/python zip''~/envs/tutorial-env/lib/python /site-packages' managing packages with pip you can installupgradeand remove packages using program called pip by default pip will install packages from the python package index<by going to it in your web browseror you can use pip' limited search feature(tutorial-envpip search astronomy skyfield elegant astronomy for python gary galactic astronomy and gravitational dynamics novas the united states naval observatory novas astronomy library astroobs provides astronomy ephemeris to plan telescope observations pyastronomy collection of astronomy related tools for python pip has number of subcommands"search""install""uninstall""freeze"etc (consult the installingindex guide for complete documentation for pip you can install the latest version of package by specifying package' name(tutorial-envpip install novas collecting novas downloading novas tar gz ( kbinstalling collected packagesnovas running setup py install for novas successfully installed novas you can also install specific version of package by giving the package name followed by =and the version number(tutorial-envpip install requests=collecting requests=using cached requests--py py -none-any whl installing collected packagesrequests successfully installed requestsif you re-run this commandpip will notice that the requested version is already installed and do nothing you can supply different version number to get that versionor you can run pip install --upgrade to upgrade the package to the latest version virtual environments and packages |
2,185 | (tutorial-envpip install --upgrade requests collecting requests installing collected packagesrequests found existing installationrequests uninstalling requests-successfully uninstalled requestssuccessfully installed requestspip uninstall followed by one or more package names will remove the packages from the virtual environment pip show will display information about particular package(tutorial-envpip show requests --metadata-version namerequests versionsummarypython http for humans home-pageauthorkenneth reitz author-emailme@kennethreitz com licenseapache location/users/akuchling/envs/tutorial-env/lib/python /site-packages requirespip list will display all of the packages installed in the virtual environment(tutorial-envpip list novas numpy (pip (requests (setuptools ( pip freeze will produce similar list of the installed packagesbut the output uses the format that pip install expects common convention is to put this list in requirements txt file(tutorial-envpip freeze requirements txt (tutorial-envcat requirements txt novas= numpy=requests=the requirements txt can then be committed to version control and shipped as part of an application users can then install all the necessary packages with install - (tutorial-envpip install - requirements txt collecting novas= (from - requirements txt (line )collecting numpy=(from - requirements txt (line )collecting requests=(from - requirements txt (line )installing collected packagesnovasnumpyrequests running setup py install for novas successfully installed novas numpyrequests managing packages with pip |
2,186 | pip has many more options consult the installing-index guide for complete documentation for pip when you've written package and want to make it available on the python package indexconsult the distributingindex guide virtual environments and packages |
2,187 | thirteen what nowreading this tutorial has probably reinforced your interest in using python -you should be eager to apply python to solving your real-world problems where should you go to learn morethis tutorial is part of python' documentation set some other documents in the set arelibrary-indexyou should browse through this manualwhich gives complete (though tersereference material about typesfunctionsand the modules in the standard library the standard python distribution includes lot of additional code there are modules to read unix mailboxesretrieve documents via httpgenerate random numbersparse command-line optionswrite cgi programscompress dataand many other tasks skimming through the library reference will give you an idea of what' available installing-index explains how to install additional modules written by other python users reference-indexa detailed explanation of python' syntax and semantics it' heavy readingbut is useful as complete guide to the language itself more python resourcesto python-related pages around the web this web site is mirrored in various places around the worldsuch as europejapanand australiaa mirror may be faster than the main sitedepending on your geographical location of user-created python modules that are available for download once you begin releasing codeyou can register it here so that others can find it code exampleslarger modulesand useful scripts particularly notable contributions are collected in book also titled python cookbook ( 'reilly associatesisbn - manipulations plus host of packages for such things as linear algebrafourier transformsnon-linear solversrandom number distributionsstatistical analysis and the like for python-related questions and problem reportsyou can post to the newsgroup comp lang pythonor send them to the mailing list at python-list@python org the newsgroup and mailing list are gatewayedso messages posted to one will automatically be forwarded to the other there are hundreds of postings dayasking (and answeringquestionssuggesting new featuresand announcing new modules mailing list archives are available at |
2,188 | before postingbe sure to check the list of frequently asked questions (also called the faqthe faq answers many of the questions that come up again and againand may already contain the solution for your problem what now |
2,189 | fourteen interactive input editing and history substitution some versions of the python interpreter support editing of the current input line and history substitutionsimilar to facilities found in the korn shell and the gnu bash shell this is implemented using the gnu readline librarywhich supports various styles of editing this library has its own documentation which we won' duplicate here tab completion and history editing completion of variable and module names is automatically enabled at interpreter startup so that the tab key invokes the completion functionit looks at python statement namesthe current local variablesand the available module names for dotted expressions such as string ait will evaluate the expression up to the final and then suggest completions from the attributes of the resulting object note that this may execute application-defined code if an object with __getattr__(method is part of the expression the default configuration also saves your history into file named python_history in your user directory the history will be available again during the next interactive interpreter session alternatives to the interactive interpreter this facility is an enormous step forward compared to earlier versions of the interpreterhoweversome wishes are leftit would be nice if the proper indentation were suggested on continuation lines (the parser knows if an indent token is required nextthe completion mechanism might use the interpreter' symbol table command to check (or even suggestmatching parenthesesquotesetc would also be useful one alternative enhanced interactive interpreter that has been around for quite some time is ipythonwhich features tab completionobject exploration and advanced history management it can also be thoroughly customized and embedded into other applications another similar enhanced interactive environment is bpython |
2,190 | interactive input editing and history substitution |
2,191 | fifteen floating point arithmeticissues and limitations floating-point numbers are represented in computer hardware as base (binaryfractions for examplethe decimal fraction has value / / / and in the same way the binary fraction has value / / / these two fractions have identical valuesthe only real difference being that the first is written in base fractional notationand the second in base unfortunatelymost decimal fractions cannot be represented exactly as binary fractions consequence is thatin generalthe decimal floating-point numbers you enter are only approximated by the binary floatingpoint numbers actually stored in the machine the problem is easier to understand at first in base consider the fraction / you can approximate that as base fraction orbetter orbetter and so on no matter how many digits you're willing to write downthe result will never be exactly / but will be an increasingly better approximation of / in the same wayno matter how many base digits you're willing to usethe decimal value cannot be represented exactly as base fraction in base / is the infinitely repeating fraction stop at any finite number of bitsand you get an approximation on most machines todayfloats are approximated using binary fraction with the numerator using the first bits starting with the most significant bit and with the denominator as power of two in the case of / the binary fraction is * which is close to but not exactly equal to the true value of / many users are not aware of the approximation because of the way values are displayed python only prints decimal approximation to the true decimal value of the binary approximation stored by the machine on most machinesif python were to print the true decimal value of the binary approximation stored for it would have to display |
2,192 | that is more digits than most people find usefulso python keeps the number of digits manageable by displaying rounded value instead just remembereven though the printed result looks like the exact value of / the actual stored value is the nearest representable binary fraction interestinglythere are many different decimal numbers that share the same nearest approximate binary fraction for examplethe numbers and and are all approximated by * since all of these decimal values share the same approximationany one of them could be displayed while still preserving the invariant eval(repr( )= historicallythe python prompt and built-in repr(function would choose the one with significant digits starting with python python (on most systemsis now able to choose the shortest of these and simply display note that this is in the very nature of binary floating-pointthis is not bug in pythonand it is not bug in your code either you'll see the same kind of thing in all languages that support your hardware' floating-point arithmetic (although some languages may not display the difference by defaultor in all output modesfor more pleasant outputyou may wish to use string formatting to produce limited number of significant digitsformat(math pi '' give significant digits format(math pi '' give digits after the point repr(math pi' it' important to realize that this isin real sensean illusionyou're simply rounding the display of the true machine value one illusion may beget another for examplesince is not exactly / summing three values of may not yield exactly either = false alsosince the cannot get any closer to the exact value of / and cannot get any closer to the exact value of / then pre-rounding with round(function cannot helpround round round =round false though the numbers cannot be made closer to their intended exact valuesthe round(function can be useful for post-rounding so that results with inexact values become comparable to one anotherround =round true floating point arithmeticissues and limitations |
2,193 | binary floating-point arithmetic holds many surprises like this the problem with " is explained in precise detail belowin the "representation errorsection see the perils of floating point for more complete account of other common surprises as that says near the end"there are no easy answers stilldon' be unduly wary of floating-pointthe errors in python float operations are inherited from the floating-point hardwareand on most machines are on the order of no more than part in ** per operation that' more than adequate for most tasksbut you do need to keep in mind that it' not decimal arithmetic and that every float operation can suffer new rounding error while pathological cases do existfor most casual use of floating-point arithmetic you'll see the result you expect in the end if you simply round the display of your final results to the number of decimal digits you expect str(usually sufficesand for finer control see the str format(method' format specifiers in formatstrings for use cases which require exact decimal representationtry using the decimal module which implements decimal arithmetic suitable for accounting applications and high-precision applications another form of exact arithmetic is supported by the fractions module which implements arithmetic based on rational numbers (so the numbers like / can be represented exactlyif you are heavy user of floating point operations you should take look at the numerical python package and many other packages for mathematical and statistical operations supplied by the scipy project see <python provides tools that may help on those rare occasions when you really do want to know the exact value of float the float as_integer_ratio(method expresses the value of float as fractionx as_integer_ratio(( since the ratio is exactit can be used to losslessly recreate the original valuex = true the float hex(method expresses float in hexadecimal (base )again giving the exact value stored by your computerx hex(' ep+ this precise hexadecimal representation can be used to reconstruct the float value exactlyx =float fromhex(' ep+ 'true since the representation is exactit is useful for reliably porting values across different versions of python (platform independenceand exchanging data with other languages that support the same format (such as java and another helpful tool is the math fsum(function which helps mitigate loss-of-precision during summation it tracks "lost digitsas values are added onto running total that can make difference in overall accuracy so that the errors do not accumulate to the point where they affect the final totalsum([ = false math fsum([ = true |
2,194 | representation error this section explains the " example in detailand shows how you can perform an exact analysis of cases like this yourself basic familiarity with binary floating-point representation is assumed representation error refers to the fact that some (mostactuallydecimal fractions cannot be represented exactly as binary (base fractions this is the chief reason why python (or perlcc++javafortranand many othersoften won' display the exact decimal number you expect why is that / is not exactly representable as binary fraction almost all machines today (november use ieee- floating point arithmeticand almost all platforms map python floats to ieee- "double precision doubles contain bits of precisionso on input the computer strives to convert to the closest fraction it can of the form / ** where is an integer containing exactly bits rewriting ~ ( **nas ~ ** and recalling that has exactly bits (is > ** but ** )the best value for is ** <true ** / ** that is is the only value for that leaves with exactly bits the best possible value for is then that quotient roundedqr divmod( ** since the remainder is more than half of the best approximation is obtained by rounding upq+ therefore the best possible approximation to / in double precision is * dividing both the numerator and denominator by two reduces the fraction to * note that since we rounded upthis is actually little bit larger than / if we had not rounded upthe quotient would have been little bit smaller than / but in no case can it be exactly / so the computer never "sees / what it sees is the exact fraction given abovethe best double approximation it can get * if we multiply that fraction by ** we can see the value out to decimal digits * / * floating point arithmeticissues and limitations |
2,195 | meaning that the exact number stored in the computer is equal to the decimal value instead of displaying the full decimal valuemany languages (including older versions of python)round the result to significant digitsformat( '' the fractions and decimal modules make these calculations easyfrom decimal import decimal from fractions import fraction fraction from_float( fraction( ( as_integer_ratio(( decimal from_float( decimal(' 'format(decimal from_float( ) '' representation error |
2,196 | floating point arithmeticissues and limitations |
2,197 | sixteen appendix interactive mode error handling when an error occursthe interpreter prints an error message and stack trace in interactive modeit then returns to the primary promptwhen input came from fileit exits with nonzero exit status after printing the stack trace (exceptions handled by an except clause in try statement are not errors in this context some errors are unconditionally fatal and cause an exit with nonzero exitthis applies to internal inconsistencies and some cases of running out of memory all error messages are written to the standard error streamnormal output from executed commands is written to standard output typing the interrupt character (usually control- or deleteto the primary or secondary prompt cancels the input and returns to the primary prompt typing an interrupt while command is executing raises the keyboardinterrupt exceptionwhich may be handled by try statement executable python scripts on bsd'ish unix systemspython scripts can be made directly executablelike shell scriptsby putting the line #!/usr/bin/env python (assuming that the interpreter is on the user' pathat the beginning of the script and giving the file an executable mode the #must be the first two characters of the file on some platformsthis first line must end with unix-style line ending ('\ ')not windows ('\ \ 'line ending note that the hashor poundcharacter'#'is used to start comment in python the script can be given an executable modeor permissionusing the chmod command chmod + myscript py on windows systemsthere is no notion of an "executable modethe python installer automatically associates py files with python exe so that double-click on python file will run it as script the extension can also be pywin that casethe console window that normally appears is suppressed the interactive startup file when you use python interactivelyit is frequently handy to have some standard commands executed every time the interpreter is started you can do this by setting an environment variable named pythonstartup problem with the gnu readline package may prevent this |
2,198 | to the name of file containing your start-up commands this is similar to the profile feature of the unix shells this file is only read in interactive sessionsnot when python reads commands from scriptand not when /dev/tty is given as the explicit source of commands (which otherwise behaves like an interactive sessionit is executed in the same namespace where interactive commands are executedso that objects that it defines or imports can be used without qualification in the interactive session you can also change the prompts sys ps and sys ps in this file if you want to read an additional start-up file from the current directoryyou can program this in the global start-up file using code like if os path isfile(pythonrc py')exec(open(pythonrc py'read()if you want to use the startup file in scriptyou must do this explicitly in the scriptimport os filename os environ get('pythonstartup'if filename and os path isfile(filename)with open(filenameas fobjstartup_file fobj read(exec(startup_filethe customization modules python provides two hooks to let you customize itsitecustomize and usercustomize to see how it worksyou need first to find the location of your user site-packages directory start python and run this codeimport site site getusersitepackages('/home/userlocal/lib/python /site-packagesnow you can create file named usercustomize py in that directory and put anything you want in it it will affect every invocation of pythonunless it is started with the - option to disable the automatic import sitecustomize works in the same waybut is typically created by an administrator of the computer in the global site-packages directoryand is imported before usercustomize see the documentation of the site module for more details appendix |
2,199 | glossary the default python prompt of the interactive shell often seen for code examples which can be executed interactively in the interpreter the default python prompt of the interactive shell when entering code for an indented code blockwhen within pair of matching left and right delimiters (parenthesessquare bracketscurly braces or triple quotes)or after specifying decorator to tool that tries to convert python code to python code by handling most of the incompatibilities which can be detected by parsing the source and traversing the parse tree to is available in the standard library as lib to standalone entry point is provided as toolsscripts/ to see to -reference abstract base class abstract base classes complement duck-typing by providing way to define interfaces when other techniques like hasattr(would be clumsy or subtly wrong (for example with magic methodsabcs introduce virtual subclasseswhich are classes that don' inherit from class but are still recognized by isinstance(and issubclass()see the abc module documentation python comes with many built-in abcs for data structures (in the collections abc module)numbers (in the numbers module)streams (in the io module)import finders and loaders (in the importlib abc moduleyou can create your own abcs with the abc module annotation label associated with variablea class attribute or function parameter or return valueused by convention as type hint annotations of local variables cannot be accessed at runtimebut annotations of global variablesclass attributesand functions are stored in the __annotations__ special attribute of modulesclassesand functionsrespectively see variable annotationfunction annotationpep and pep which describe this functionality argument value passed to function (or methodwhen calling the function there are two kinds of argumentkeyword argumentan argument preceded by an identifier ( name=in function call or passed as value in dictionary preceded by *for example and are both keyword arguments in the following calls to complex()complex(real= imag= complex(**{'real' 'imag' }positional argumentan argument that is not keyword argument positional arguments can appear at the beginning of an argument list and/or be passed as elements of an iterable preceded by for example and are both positional arguments in the following callscomplex( complex(*( ) |
Subsets and Splits