id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
17,900 | sys exc_info(function the following read-only attributes are available in traceback objectsattribute description tb_next next level in the stack trace (toward the execution frame where the exception occurredexecution frame object of the current level line number where the exception occurred instruction being executed i... |
17,901 | types and objects attribute description start stop step lower bound of the slicenone if omitted upper bound of the slicenone if omitted stride of the slicenone if omitted slice objects also provide single methods indices(lengththis function takes length and returns tuple (start,stop,stridethat indicates how the slice w... |
17,902 | attributes of an object and is called immediately after an object has been newly created the _del_ (method is invoked when an object is about to be destroyed this method is invoked only when an object is no longer in use it' important to note that the statement del only decrements an object' reference count and doesn' ... |
17,903 | types and objects if string expression cannot be createdthe convention is for _repr_ (to return string of the form as shown heref open("foo" repr(fa "the _str_ (method is called by the built-in str(function and by functions related to printing it differs from _repr_ (in that the string it returns can be more concise an... |
17,904 | table continued method result _eq_ (self,other_ _ne_ (self,otherself =other self !other it is not necessary for an object to implement all of the operations in table howeverif you want to be able to compare objects using =or use an object as dictionary keythe _eq_ (method should be defined if you want to be able to sor... |
17,905 | types and objects attribute wrapping and descriptors subtle aspect of attribute manipulation is that sometimes the attributes of an object are wrapped with an extra layer of logic that interact with the getsetand delete operations described in the previous section this kind of wrapping is accomplished by creating descr... |
17,906 | for manipulating individual itemsthe _getitem_ (method can return an item by key value the key can be any python object but is typically an integer for sequences the _setitem_ (method assigns value to an element the _delitem_ (method is invoked whenever the del operation is applied to single element the _contains_ (met... |
17,907 | types and objects implicitly perform iteration for examplethe statement for in is carried out by performing steps equivalent to the following_iter _iter_ (while tryx _iter next()(#_iter _next_ (in python except stopiterationbreak do statements in body of for loop mathematical operations table lists special methods that... |
17,908 | table continued method result _rpow_ (self,other_ _rlshift_ (self,other_ _rrshift_ (self,otherother *self other <self other >self other self other self other self self +other self -other self *other self /other (python onlyself /other (python self //other self %other self **other self &other self |other self ^other sel... |
17,909 | types and objects behavior can be enabled in python as an optional feature by including the statement from _future_ import division in program the conversion methods _int_ () _long_ () _float_ ()and _complex_ (convert an object into one of the four built-in numerical types these methods are invoked by explicit type con... |
17,910 | table continued method description _exit_ (selftypevaluetbcalled when leaving context if an exception occurredtypevalueand tb have the exception typevalueand traceback information the primary use of the context management interface is to allow for simplified resource control on objects involving system state such as op... |
17,911 | lib fl ff |
17,912 | operators and expressions his describes python' built-in operatorsexpressionsand evaluation rules although much of this describes python' built-in typesuser-defined objects can easily redefine any of the operators to provide their own behavior operations on numbers the following operations can be applied to all numeric... |
17,913 | operators and expressions the bitwise operators assume that integers are represented in ' complement binary representation and that the sign bit is infinitely extended to the left some care is required if you are working with raw bit-patterns that are intended to map to native integers on the hardware this is because p... |
17,914 | if either operand is floating-point numberthe other is converted to float otherwiseboth numbers must be integers and no conversion is performed for user-defined objectsthe behavior of expressions involving mixed operands depends on the implementation of the object as general rulethe interpreter does not try to perform ... |
17,915 | operators and expressions all sequences can be unpacked into sequence of variable names for exampleitems , , items letters "abcx, , letters ' ' ' ' 'cdatetime (( )( "am")(month,day,year),(hour,minute,am_pmdatetime when unpacking values into variablesthe number of variables must exactly match the number of items in the ... |
17,916 | 'helloin 'hello worldproduces true it is important to note that the in operator does not support wildcards or any kind of pattern matching for thisyou need to use library module such as the re module for regular expression patterns the for in operator iterates over all the elements of sequence and is described further ... |
17,917 | sequences are compared using the operators ===and !when comparing two sequencesthe first elements of each sequence are compared if they differthis determines the result if they're the samethe comparison moves to the second element of each sequence this process continues until two different elements are found or no more... |
17,918 | table continued character output format , floating point as [-] dddddde+-xx use % or % for exponents less than - or greater than the precisionotherwiseuse % string or any object the formatting code uses str(to generate strings produces the same string as produced by repr(single character literal between the character a... |
17,919 | operators and expressions $var symbols in stringsfor exampleif you have dictionary of valuesyou can expand those values into fields within formatted string as followsstock 'name'goog''shares 'price "%(shares) of %(name) at %(price) fstock " shares of goog at the following code shows how to expand the values of currentl... |
17,920 | the general format of specifier is [[fill[align]][sign][ ][widthprecision][typewhere each part enclosed in [is optional the width specifier specifies the minimum field width to useand the align specifier is one of ''or '^for leftrightand centered alignment within the field an optional fill character fill is used to pad... |
17,921 | operators and expressions '{ : }format(yr '{ :+ }format(yr '{ :+ }format(yr '{ :+ %}format(yr + + '+ + %parts of format specifier can optionally be supplied by other fields supplied to the format function they are accessed using the same syntax as normal fields in format string for exampley '{ :{width{precision} }forma... |
17,922 | operations on sets the set and frozenset type support number of common set operationsoperation description len(smax(smin(sunion of and intersection of and set difference symmetric difference number of items in the set maximum value minimum value the result of unionintersectionand difference operations will have the sam... |
17,923 | operators and expressions the attribute operator the dot operator is used to access the attributes of an object here' an examplefoo print foo foo bar( , , more than one dot operator can appear in single expressionsuch as in foo the dot operator can also be applied to the intermediate results of functionsas in foo bar( ... |
17,924 | function description repr(xformat( [,format_spec]eval(strtuple(sconverts object to an expression string converts object to formatted string evaluates string and returns an object converts to tuple converts to list converts to set creates dictionary must be sequence of (key,valuetuples converts to frozen set converts an... |
17,925 | when you use an expression to determine true or false valuetrueany nonzero numbernonempty stringlisttupleor dictionary is taken to be true falsezerononeand empty liststuplesand dictionaries evaluate as false boolean expressions are evaluated from left to right and consume the right operand only if it' needed to determi... |
17,926 | table continued operator name is yx is not in sx not in not and or lambda argsexpr logical negation logical and logical or anonymous function the order of evaluation is not determined by the types of and in table soeven though user-defined objects can redefine individual operatorsit is not possible to customize the und... |
17,927 | lib fl ff |
17,928 | program structure and control flow his covers the details of program structure and control flow topics include conditionalsiterationexceptionsand context managers program structure and execution python programs are structured as sequence of statements all language featuresincluding variable assignmentfunction definitio... |
17,929 | program structure and control flow if no action is to be takenyou can omit both the else and elif clauses of conditional use the pass statement if no statements exist for particular clauseif expressionpass elsestatements do nothing loops and iteration you implement loops using the for and while statements here' an exam... |
17,930 | statements + python provides built-in functionenumerate()that can be used to simplify this codefor , in enumerate( )statements enumerate(screates an iterator that simply returns sequence of tuples ( [ ])( [ ])( [ ])and so on another common looping problem concerns iterating in parallel over two or more sequences--for e... |
17,931 | program structure and control flow the break and continue statements apply only to the innermost loop being executed if it' necessary to break out of deeply nested loop structureyou can use an exception python doesn' provide "gotostatement you can also attach the else statement to loop constructsas in the following exa... |
17,932 | when an exception occursthe interpreter stops executing statements in the try block and looks for an except clause that matches the exception that has occurred if one is foundcontrol is passed to the first statement in the except clause after the except clause is executedcontrol continues with the first statement that ... |
17,933 | program structure and control flow when catching all exceptionsyou should take care to report accurate error information to the user for examplein the previous codean error message and the associated exception value is being logged if you don' include any information about the exception valueit can make it very difficu... |
17,934 | table built-in exceptions exception description baseexception generatorexit keyboardinterrupt systemexit exception stopiteration standarderror arithmeticerror floatingpointerror zerodivisionerror assertionerror attributeerror environmenterror ioerror oserror eoferror importerror lookuperror indexerror keyerror memoryer... |
17,935 | program structure and control flow exceptions are organized into hierarchy as shown in the table all the exceptions in particular group can be caught by specifying the group name in an except clause here' an exampletrystatements except lookuperrorstatements catch indexerror or keyerror or trystatements except exception... |
17,936 | def error ()raise hostnameerror("unknown host"def error ()raise timeouterror("timed out"tryerror (except networkerror as eif type(eis hostnameerrorperform special actions for this kind of error in this casethe except networkerror statement catches any exception derived from networkerror to find the specific type of err... |
17,937 | program structure and control flow the with obj statement accepts an optional as var specifier if giventhe value returned by obj _enter_ (is placed into var it is important to emphasize that obj is not necessarily the value assigned to var the with statement only works with objects that support the context management p... |
17,938 | assertions and _debug_ the assert statement can introduce debugging code into program the general form of assert is assert test [msgwhere test is an expression that should evaluate to true or false if test evaluates to falseassert raises an assertionerror exception with the optional message msg supplied to the assert s... |
17,939 | lib fl ff |
17,940 | functions and functional programming ubstantial programs are broken up into functions for better modularity and ease of maintenance python makes it easy to define functions but also incorporates surprising number of features from functional programming languages this describes functionsscoping rulesclosuresdecoratorsge... |
17,941 | functions and functional programming in additionthe use of mutable objects as default values may lead to unintended behaviordef foo(xitems=[])items append(xreturn items foo( returns [ foo( returns [ foo( returns [ notice how the default argument retains modifications made from previous invocations to prevent thisit is ... |
17,942 | if the last argument of function definition begins with **all the additional keyword arguments (those that don' match any of the other parameter namesare placed in dictionary and passed to the function this can be useful way to write functions that accept large number of potentially open-ended configuration options tha... |
17,943 | functions and functional programming programming style that is best avoided because such functions can become source of subtle programming errors as programs grow in size and complexity (for exampleit' not obvious from reading function call if function has side effectssuch functions interact poorly with programs involv... |
17,944 | def foo()global 'ais in global namespace foo( is now is still python supports nested function definitions here' an exampledef countdown(start) start def display()nested function definition print(' -minus %dnwhile display( - variables in nested functions are bound using lexical scoping that isnames are resolved by first... |
17,945 | functions and functional programming if local variable is used before it' assigned valuean unboundlocalerror exception is raised here' an example that illustrates one scenario of how this might occuri def foo() print(iresults in unboundlocalerror exception in this functionthe variable is defined as local variable (beca... |
17,946 | in this examplenotice how the function helloworld(uses the value of that' defined in the same environment as where helloworld(was defined thuseven though there is also an defined in foo py and that' where helloworld(is actually being calledthat value of is not the one that' used when helloworld(executes when the statem... |
17,947 | functions and functional programming executesit calls urlopen(urlwith the value of url that was originally supplied to page(with little inspectionyou can view the contents of variables that are carried along in closure for examplepython _closure_ (,python _closure_ [ cell_contents jython _closure_ [ cell_contents closu... |
17,948 | decorators decorator is function whose primary purpose is to wrap another function or class the primary purpose of this wrapping is to transparently alter or enhance the behavior of the object being wrapped syntacticallydecorators are denoted using the special symbol as follows@trace def square( )return * the preceding... |
17,949 | functions and functional programming in this casethe decorators are applied in the order listed the result is the same as thisdef grok( )pass grok foo(bar(spam(grok)) decorator can also accept arguments here' an example@eventhandler('button'def handle_button(msg)@eventhandler('reset'def handle_reset(msg)if arguments ar... |
17,950 | def countdown( )print("counting down from %dnwhile yield - return if you call this functionyou will find that none of its code starts executing for examplec countdown( insteada generator object is returned the generator objectin turnexecutes the function whenever next(is called (or _next_ (in python here' an examplec n... |
17,951 | functions and functional programming inside the generator functionclose(is signaled by generatorexit exception occurring on the yield statement you can optionally catch this exception to perform cleanup actions def countdown( )print("counting down from %dntrywhile yield except generatorexitprint("only made it to %dnalt... |
17,952 | def coroutine(func)def start(*args,**kwargs) func(*args,**kwargsg next(return return start using this decoratoryou would write and use coroutines using@coroutine def receiver()print("ready to receive"while truen (yieldprint("got %snexample use receiver( send("hello world"note no initial next(needed coroutine will typic... |
17,953 | functions and functional programming in this casewe use the coroutine in the same way as before howevernow calls to send(also produce result for examples line_splitter("," next(ready to split send(" , , "[' '' ''cs send(" , , "[' '' '' 'understanding the sequencing of this example is critical the first next(call advanc... |
17,954 | here is an example of using these functions to set up processing pipelinewwwlogs find("www","access-log*"files opener(wwwlogslines cat(filespylines grep("python"linesfor line in pylinessys stdout write(linein this examplethe program is processing all lines in all "access-log*files found within all subdirectories of top... |
17,955 | functions and functional programming @coroutine def grep(patterntarget)while trueline (yieldif pattern in linetarget send(line@coroutine def printer()while trueline (yieldsys stdout write(linehere is how you would link these coroutines to create dataflow processing pipelinefinder find_files(opener(cat(grep("python",pri... |
17,956 | this syntax is roughly equivalent to the following codes [for item in iterable if condition for item in iterable if condition for itemn in iterablenif conditionns append(expressionto illustratehere are some more examplesa [- , , ,- , , 'abcc [ * for in ad [ for in if > [( ,yfor in for in if [( , )( , )( , ) [math sqrt(... |
17,957 | functions and functional programming unlike list comprehensiona generator expression does not actually create list or immediately evaluate the expression inside the parentheses insteadit creates generator object that produces the values on demand via iteration here' an examplea [ ( * for in ab next( next( the differenc... |
17,958 | aa ibm cat msft ge msft ibm here is declarative-style program that calculates the total cost by summing up the second column multiplied by the third columnlines open("portfolio txt"fields (line split(for line in linesprint(sum(float( [ ]float( [ ]for in fields)in this programwe really aren' concerned with the mechanics... |
17,959 | functions and functional programming the lambda operator anonymous functions in the form of an expression can be created using the lambda statementlambda args expression args is comma-separated list of argumentsand expression is an expression involving those arguments here' an examplea lambda , + ( , gets the code defi... |
17,960 | def genflatten(lists)for in listsif isinstance( ,list)for item in genflatten( )yield item elseyield item care should also be taken when mixing recursive functions and decorators if decorator is applied to recursive functionall inner recursive calls now get routed through the decorated version for example@locked def fac... |
17,961 | functions and functional programming to fix thiswrite decorator functions so that they propagate the function name and documentation string for exampledef wrap(func)call(*args,**kwargs)return func(*args,**kwargscall _doc_ func _doc_ call _name_ func _name_ return call because this is common problemthe functools module ... |
17,962 | eval()exec()and compile(the eval(str [,globals [,locals]]function executes an expression string and returns the result here' an examplea eval(' *math sin( + 'similarlythe exec(str [globals [locals]]function executes string containing arbitrary python code the code supplied to exec(is executed as if the code actually ap... |
17,963 | lib fl ff |
17,964 | classes and object-oriented programming lasses are the mechanism used to create new kinds of objects this covers the details of classesbut is not intended to be an in-depth reference on object-oriented programming and design it' assumed that the reader has some prior experience with data structures and object-oriented ... |
17,965 | classes and object-oriented programming it' important to note that class statement by itself doesn' create any instances of the class (for exampleno accounts are actually created in the preceding examplerathera class merely sets up the attributes that will be common to all the instances that will be created later in th... |
17,966 | class foo(object)def bar(self)print("bar!"def spam(self)bar(selfincorrect'bargenerates nameerror self bar(this works foo bar(selfthis also works the lack of scoping in classes is one area where python differs from +or java if you have used those languagesthe self parameter in python is the same as the this pointer the ... |
17,967 | classes and object-oriented programming subclass can add new attributes to the instances by defining its own version of _init_ (for examplethis version of evilaccount adds new attribute evilfactorclass evilaccount(account)def _init_ (self,name,balance,evilfactor)account _init_ (self,name,balanceinitialize account self ... |
17,968 | class depositcharge(object)fee def deposit_fee(self)self withdraw(self feeclass withdrawcharge(object)fee def withdraw_fee(self)self withdraw(self feeclass using multiple inheritance class mostevilaccount(evilaccountdepositchargewithdrawcharge)def deposit(self,amt)self deposit_fee(super(mostevilaccount,selfdeposit(amtd... |
17,969 | classes and object-oriented programming oopsla' subtle aspect of this algorithm is that certain class hierarchies will be rejected by python with typeerror here' an exampleclass (object)pass class ( )pass class ( , )pass typeerror can' create consistent method resolution order_ in this casethe method resolution algorit... |
17,970 | static methods and class methods in class definitionall functions are assumed to operate on an instancewhich is always passed as the first parameter self howeverthere are two other common kinds of methods that can be defined static method is an ordinary function that just happens to live in the namespace defined by cla... |
17,971 | classes and object-oriented programming in this examplenotice how the class twotimes is passed to mul(as an object although this example is esotericthere are practicalbut subtleuses of class methods as an examplesuppose that you defined class that inherited from the date class shown previously and customized it slightl... |
17,972 | the resulting circle object behaves as followsc circle( radius area perimeter area traceback (most recent call last)file ""line in attributeerrorcan' set attribute in this examplecircle instances have an instance variable radius that is stored area and perimeter are simply computed from that value the @property decorat... |
17,973 | classes and object-oriented programming class foo(object)def _init_ (self,name)self _name name @property def name(self)return self _name @name setter def name(self,value)if not isinstance(value,str)raise typeerror("must be string!"self _name value @name deleter def name(self)raise typeerror("can' delete name" foo("guid... |
17,974 | class typedproperty(object)def _init_ (self,name,type,default=none)self name "_name self type type self default default if default else type(def _get_ (self,instance,cls)return getattr(instance,self name,self defaultdef _set_ (self,instance,value)if not isinstance(value,self type)raise typeerror("must be %sself typeset... |
17,975 | classes and object-oriented programming class ( )def _init_ (self) _init_ (selfself _x def _spam(self)pass mangled to self _b_ _x mangled to _b_ _spam(although this scheme provides the illusion of data hidingthere' no strict mechanism in place to actually prevent access to the "privateattributes of class in particulari... |
17,976 | the creation of an instance is carried out in two steps using the special method _new_ ()which creates new instanceand _init_ ()which initializes it for examplethe operation circle( performs these stepsc circle _new_ (circle if isinstance( ,circle)circle _init_ ( , the _new_ (method of class is something that is rarely... |
17,977 | classes and object-oriented programming can be problem for examplesuppose you had an object that was implementing variant of the "observer pattern class account(object)def _init_ (self,name,balance)self name name self balance balance self observers set(def _del_ (self)for ob in self observersob close(del self observers... |
17,978 | def _del_ (self)acc self accountref(get account if accunregister if still exists acc unregister(selfdef update(self)print("balance is % fself accountref(balancedef close(self)print("account no longer in use"example setup account('dave', a_ob accountobserver(ain this examplea weak reference accountref is created to acce... |
17,979 | classes and object-oriented programming that casethe set and delete operation will be carried out by the set and delete functions associated with the property for attribute lookup such as obj namethe special method obj _getattrribute_ ("name"is invoked this method carries out the search process for finding the attribut... |
17,980 | create large number of objectsusing _slots_ can result in substantial reduction in memory use and execution time be aware that the use of _slots_ has tricky interaction with inheritance if class inherits from base class that uses _slots_ _it also needs to define _slots_ for storing its own attributes (even if it doesn'... |
17,981 | classes and object-oriented programming creates string that' intended for nice output formatting (this is the string that would be produced by the print statementthe other operatorssuch as _add_ (and _sub_ ()implement mathematical operations delicate matter with these operators concerns the order of operands and type c... |
17,982 | function returns true if an objectobjbelongs to the class cname or any class derived from cname here' an exampleclass (object)pass class ( )pass class (object)pass ( ( (instance of 'ainstance of 'binstance of 'ctype(aisinstance( ,aisinstance( ,aisinstance( ,creturns the class object returns true returns trueb derives f... |
17,983 | classes and object-oriented programming def _subclasscheck_ (self,sub)return any( in self implementors for in sub mro()nowuse the above object ifoo iclass(ifoo register(fooifoo register(fooproxyin this examplethe class iclass creates an object that merely groups collection of other classes together in set the register(... |
17,984 | def name(self)pass the definition of an abstract class needs to set its metaclass to abcmeta as shown (alsobe aware that the syntax differs between python and this is required because the implementation of abstract classes relies on metaclass (described in the next sectionwithin the abstract classthe @abstractmethod an... |
17,985 | classes and object-oriented programming the abstract class mechanism addresses this issue by allowing preexisting objects to be organized into user-definable type hierarchies moreoversome library modules aim to organize the built-in types according to different capabilities that they possess the collections module cont... |
17,986 | number of ways firstthe class can explicitly specify its metaclass by either setting _metaclass_ class variable (python )or supplying the metaclass keyword argument in the tuple of base classes (python class foo__metaclass__ type in python use the syntax class foo(metaclass=typeif no metaclass is explicitly specifiedth... |
17,987 | classes and object-oriented programming this base class is then used as the parent for all objects that are to be documented for exampleclass foo(documented)spam(self, , )"spam does somethingpass this example illustrates one of the major uses of metaclasseswhich is that of inspecting and gathering information about cla... |
17,988 | although metaclasses make it possible to drastically alter the behavior and semantics of user-defined classesyou should probably resist the urge to use metaclasses in way that makes classes work wildly different from what is described in the standard python documentation users will be confused if the classes they must ... |
17,989 | lib fl ff |
17,990 | modulespackagesand distribution arge python programs are organized into modules and packages in additiona large number of modules are included in the python standard library this describes the module and package system in more detail in additionit provides information on how to install third-party modules and distribut... |
17,991 | modulespackagesand distribution it is important to emphasize that import executes all of the statements in the loaded source file if module carries out computation or produces output in addition to defining variablesfunctionsand classesyou will see the result alsoa common confusion with modules concerns the access to c... |
17,992 | importing selected symbols from module the from statement is used to load specific definitions within module into the current namespace the from statement is identical to import except that instead of creating name referring to the newly created module namespaceit places references to one or more of the objects defined... |
17,993 | modulespackagesand distribution following codethe call to bar(results in call to spam foo()not the redefined foo(that appears in the previous code examplefrom spam import bar def foo()print(" ' different foo"bar(when bar calls foo()it calls spam foo()not the definition of foo(above another common confusion with the fro... |
17,994 | moduleyou can put code for testing the features of your library inside an if statement as shown and simply run python on your module as the main program to run it that code won' run for users who import your library the module search path when loading modulesthe interpreter searches the list of directories in sys path ... |
17,995 | packages containing collection of modules built-in modules written in and linked into the python interpreter when looking for module (for examplefoo)the interpreter searches each of the directories in sys path for the following files (listed in search order) directoryfoodefining package foo pydfoo sofoomodule soor foom... |
17,996 | module reloading and unloading python provides no real support for reloading or unloading of previously imported modules although you can remove module from sys modulesthis does not generally unload module from memory this is because references to the module object may still exist in other program components that used ... |
17,997 | png py tiff py jpeg py the import statement is used to load modules from package in number of waysn import graphics primitive fill this loads the submodule graphics primitive fill the contents of this module have to be explicitly namedsuch as graphics primitive fill floodfill(img, , ,colorn from graphics primitive impo... |
17,998 | same directory as the file fill py great care should be taken to avoid using statement such as import module to import package submodule in older versions of pythonit was unclear whether the import module statement was referring to standard library module or submodule of package older versions of python would first try... |
17,999 | modulespackagesand distribution distributing python programs and libraries to distribute python programs to othersyou should use the distutils module as preparationyou should first cleanly organize your work into directory that has readme filesupporting documentationand your source code typicallythis directory will con... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.