id
int64
0
25.6k
text
stringlengths
0
4.59k
3,600
the setup and teardown methods for the module are executed at the beginning and end of the session then the lone module-level test function is run nextthe setup method for the first class is executedfollowed by the two tests for that class these tests are each individually wrapped in separate setup_method and teardown_...
3,601
each of the three test methods accepts parameter named valid_statsthis parameter is created by calling the pytest_funcarg__valid_stats function defined at the top of the file it can also be defined in file called conftest py if the funcarg is needed by multiple modules the conftest py file is parsed by py test to load ...
3,602
return dir def test_osfiles(temp_dir)os mkdir(os path join(temp_dir' ')os mkdir(os path join(temp_dir' ')dir_contents os listdir(temp_dirassert len(dir_contents= assert 'ain dir_contents assert 'bin dir_contents the funcarg creates new empty temporary directory for files to be created in then it adds finalizer call to ...
3,603
import time def pytest_funcarg__echoserver(request)def setup() subprocess popen['python ''echo_server py']time sleep( return def cleanup( ) terminate(return request cached_setupsetup=setupteardown=cleanupscope="session"def pytest_funcarg__clientsocket(request) socket socket(socket af_inetsocket sock_streams connect(('l...
3,604
instead of returning funcarg directlythe parent function returns the results of call to request cached_setup it accepts two arguments for the setup and teardown functions (which we just created)and scope argument this last argument should be one of the three strings "function""module"or "session"it determines just how ...
3,605
since skipping an individual test method or function based on certain conditional is one of the most common uses of test skippingpy test provides convenience decorator that allows us to do this in one line the decorator accepts single stringwhich can contain any executable python code that evaluates to boolean value fo...
3,606
status status upper(if status not in self allowed_statusesraise valueerror"{is not valid statusformat(status)key "flightno:{}format(flightvalue "{}|{}formatdatetime datetime now(isoformat()statusself redis set(keyvaluethere are lot of things we ought to test in that change_status method we should check that it raises t...
3,607
this testwritten using py test syntaxasserts that the correct exception is raised when an inappropriate argument is passed in in additionit creates mock object for the set method and makes sure that it is never called if it wasit would mean there was bug in our exception handling code simply replacing the method worked...
3,608
thenafter calling our change_status method with known valueswe use the mock class' assert_called_once_with function to ensure that the now function was indeed called exactly once with no arguments we then call it second time to prove that the redis set method was called with arguments that were formatted as we expected...
3,609
in generalwe should be quite stingy with mocks if we find ourselves mocking out multiple elements in given unit testwe may end up testing the mock framework rather than our real code this serves no useful purpose whatsoeverafter allmocks are well-tested alreadyif our code is doing lot of thisit' probably another sign t...
3,610
the output is as followsname stmts exec cover coverage_unittest stats total this basic report lists the files that were executed (our unit test and module it importedthe number of lines of code in each fileand the number that were executed by the test are also listed the two numbers are then combined to estimate the am...
3,611
the textual report is sufficientbut if we use the command coverage htmlwe can get an even fancier interactive html report that we can view in web browser the web page even highlights which lines in the source code were and were not tested here' how it lookswe can use the coverage py module with py test as well we'll ne...
3,612
bear in mind that while percent code coverage is lofty goal that we should all strive for percent coverage is not enoughjust because statement was tested does not mean that it was tested properly for all possible inputs case study let' walk through test-driven development by writing smalltestedcryptography application ...
3,613
given keywordtrainwe can encode the message encoded in python as follows repeat the keyword and message together such that it is easy to map letters from one to the othere for each letter in the plain textfind the row that begins with that letter in the table find the column with the letter associated with the keyword ...
3,614
this test failsnaturallybecause we aren' importing vigenerecipher class anywhere let' create new module to hold that class let' start with the following vigenerecipher classclass vigenerecipherdef __init__(selfkeyword)self keyword keyword def encode(selfplaintext)return "xecwqxuivcrkhwaif we add from vigenere_cipher im...
3,615
now that we have some test caseslet' think about how to implement our encoding algorithm writing code to use table like we used in the earlier manual algorithm is possiblebut seems complicatedconsidering that each row is just an alphabet rotated by an offset number of characters it turns out ( asked wikipediathat we ca...
3,616
before writing this testi expected to write extend_keyword as standalone function that accepted keyword and an integer but as started drafting the testi realized it made more sense to use it as helper method on the vigenerecipher class this shows how test-driven development can help design more sensible apis here' the ...
3,617
assert separate_character(" "" "="ndef test_decode()cipher vigenerecipher("train"decoded cipher decode("xecwqxuivcrkhwa"assert decoded ="encodedinpythonhere' the separate_character functiondef separate_character(cypherkeyword)cypher cypher upper(keyword keyword upper(cypher_num ord(cypherord(' 'keyword_num ord(keywordo...
3,618
this is the final benefit of test-driven developmentand the most important once the tests are writtenwe can improve our code as much as we like and be confident that our changes didn' break anything we have been testing for furthermorewe know exactly when our refactor is finishedwhen the tests all pass of courseour tes...
3,619
we used py test in our case studybut we didn' touch on any features that wouldn' have been easily testable using unittest try adapting the tests to use test skipping or funcargs try the various setup and teardown methodsand compare their use to funcargs which feels more natural to youin our case studywe have lot of tes...
3,620
concurrency is the art of making computer do (or appear to domultiple things at once historicallythis meant inviting the processor to switch between different tasks many times per second in modern systemsit can also literally mean doing two or more things simultaneously on separate processor cores concurrency is not in...
3,621
threads most oftenconcurrency is created so that work can continue happening while the program is waiting for / to happen for examplea server can start processing new network request while it waits for data from previous request to arrive an interactive program might render an animation or perform calculation while wai...
3,622
the new thread doesn' start running until we call the start(method on the object in this casethe thread immediately pauses to wait for input from the keyboard in the meantimethe original thread continues executing at the point start was called it starts calculating squares inside while loop the condition in the while l...
3,623
'quebec city''reginaclass tempgetter(thread)def __init__(selfcity)super(__init__(self city city def run(self)url_template ''weather? ={},ca&units=metric'response urlopen(url_template format(self city)data json loads(response read(decode()self temperature data['main']['temp'threads [tempgetter(cfor in citiesstart time t...
3,624
at this pointwe can print the temperature that was stored on each thread object notice once again that we can access data that was constructed within the thread from the main thread in threadsall state is shared by default executing this code on my mbit connection takes about two tenths of secondit is degc in edmonton ...
3,625
the solution to this problem in threaded programming is to "synchronizeaccess to any code that reads or writes shared variable there are few different ways to do thisbut we won' go into them here so we can focus on more pythonic constructs the synchronization solution worksbut it is way too easy to forget to apply it w...
3,626
while the gil is problem in the reference implementation of python that most people useit has been solved in some of the nonstandard implementations such as ironpython and jython unfortunatelyat the time of publicationnone of these support python thread overhead one final limitation of threads as compared to the asynch...
3,627
let' try to parallelize compute-heavy operation using similar constructs to those provided by the threading apifrom multiprocessing import processcpu_count import time import os class muchcpu(process)def run(self)print(os getpid()for in range( )pass if __name__ ='__main__'procs [muchcpu(for in range(cpu_count()) time t...
3,628
work took seconds the first four lines are the process id that was printed inside each muchcpu instance the last line shows that the million iterations can run in about seconds on my machine during that secondsmy process monitor indicated that all four of my cores were running at percent if we subclass threading thread...
3,629
the primary advantage of pools is that they abstract away the overhead of figuring out what code is executing in the main process and which code is running in the subprocess as with the threading api that multiprocessing mimicsit can often be hard to remember who is executing what the pool abstraction restricts the num...
3,630
elsefactors [valuereturn factors if __name__ ='__main__'pool pool(to_factor random randint( for in range( results pool map(prime_factorto_factorfor valuefactors in zip(to_factorresults)print("the factors of {are {}format(valuefactors)let' focus on the parallel processing aspects as the brute force recursive algorithm f...
3,631
queues if we need more control over communication between processeswe can use queue queue data structures are useful for sending messages from one process into one or more other processes any picklable object can be sent into queuebut remember that pickling can be costly operationso keep such objects small to illustrat...
3,632
pathnames [ for in path('listdir(if isfile()paths [pathnames[ ::cpusfor in range(cpus)query_queues [queue(for in range(cpus)results_queue queue(search_procs process(target=searchargs=(pqresults_queue)for pq in zip(pathsquery_queuesfor proc in search_procsproc start(for easier descriptionlet' assume cpu_count is four no...
3,633
the problems with multiprocessing as threads domultiprocessing also has problemssome of which we have already discussed there is no best way to do concurrencythis is especially true in python we always need to examine the parallel problem to figure out which of the many available solutions is the best one for that prob...
3,634
let' do another file search example in the last sectionwe implemented version of the unix grep command this timelet' do simple version of the find command the example will search the entire filesystem for paths that contain given string of charactersfrom concurrent futures import threadpoolexecutor from pathlib import ...
3,635
this code consists of function named find_files that is run in separate thread (or processif we used processpoolexecutorthere isn' anything particularly special about this functionbut note how it does not access any global variables all interaction with the external environment is passed into the function or returned f...
3,636
once the executor has been constructedwe submit job to it using the root directory the submit(method immediately returns future objectwhich promises to give us result eventually the future is placed on the queue the loop then repeatedly removes the first future from the queue and inspects it if it is still runningit ge...
3,637
asyncio solves this by creating set of coroutines that use the yield from syntax to return control to the event loop immediately the event loop takes care of checking whether the blocking call has completed and performing any subsequent tasksjust like we did manually in the previous section asyncio in action canonical ...
3,638
now look little more closely at that five_sleepers future ignore the decorator for few paragraphswe'll get back to it the coroutine first constructs five instances of the random_sleep future the resulting futures are wrapped in an asyncio async taskwhich adds them to the loop' task queue so they can execute concurrentl...
3,639
it' still good idea to avoid accessing shared state from inside coroutine it makes your code much easier to reason about more importantlyeven though an ideal world might have all asynchronous execution happen inside coroutinesthe reality is that some futures are executed behind the scenes inside threads or processes st...
3,640
domain +data[pointer:pointer+part_lengthbpointer +part_length part_length data[pointer ip ip_map get(domain 'return domainip def create_response(dataip)ba bytearray packet ba(data[: ]ba([ ]data[ : packet +ba( data[ :packet +ba([ ]for in ip split(')packet append(int( )return packet class dnsprotocol(asyncio datagramprot...
3,641
this example sets up dictionary that dumbly maps few domains to ipv addresses it is followed by two functions that extract information from binary dns query packet and construct the response we won' be discussing theseif you want to know more about dns read rfc ("request for comment"the format for defining most interne...
3,642
behind the scenesthe transport has set up task on the event loop that is listening for incoming udp connections all we have to dothenis start the event loop running with the call to loop run_forever(so that task can process these packets when the packets arrivethey are processed on the protocol and everything just work...
3,643
curr - return json dumps(numsencode(@asyncio coroutine def sort_request(readerwriter)print("received connection"length yield from reader read( data yield from reader readexactlyint from_bytes(length'big')result yield from asyncio get_event_loop(run_in_executornonesort_in_processdataprint("sorted list"writer write(resul...
3,644
secondthe two methods are very linearit looks like code is being executed one line after another of coursein asynciothis is an illusionbut we don' have to worry about shared memory or concurrency primitives streams the previous example should look familiar by now as it has similar boilerplate to other asyncio programs ...
3,645
you may be wondering ifinstead of running multiple processes inside an event loopit might be better to run multiple event loops in different processes the answer is"maybehoweverdepending on the exact problem spacewe are probably better off running independent copies of program with single event loop than to try to coor...
3,646
when dealing with fileswe have to think about the exact layout of the bytes in the compressed file our file will store two byte little-endian integers at the beginning of the file representing the width and height of the completed file then it will write bytes representing the bit chunks of each row now before we start...
3,647
the method compresses the data using run-length encoding and returns bytearray containing the packed data where bitarray is like list of ones and zerosa bytearray is like list of byte objects (each byteof coursecontaining ones or zerosthe algorithm that performs the compression is pretty simple (although ' like to poin...
3,648
row_compressors append(compressorcompressed bytearray(for compressor in row_compressorscompressed extend(compressor result()return compressed this example barely needs explainingit splits the incoming bits into rows based on the width of the image using the same split_bits function we have already defined (hooray for b...
3,649
having written all this codewe are finally able to test whether thread pools or process pools give us better performance created large ( pixelsblack and white image and ran it through both pools the processpool takes about seconds to process the image on my systemwhile the threadpool consistently takes about thusas we ...
3,650
now that we are running executors inside executorsthere are four combinations of threads and process pools that we can be using to compress images they each have quite different timing profilesprocess pool per row process pool per image seconds thread pool per image seconds thread pool per row seconds seconds as we mig...
3,651
for completenesshere' the code that used to decompress the rle images to confirm that the algorithm was working correctly (indeedit wasn' until fixed bugs in both compression and decompressionand ' still not sure if it is perfect should have used test-driven development!)from pil import image import sys def decompress(...
3,652
exercises we've covered several different concurrency paradigms in this and still don' have clear idea of when each one is useful as we saw in the case studyit is often good idea to prototype few different strategies before committing to one concurrency in python is huge topic and an entire book of this size could not ...
3,653
summary this ends our exploration of object-oriented programming with topic that isn' very object-oriented concurrency is difficult problem and we've only scratched the surface while the underlying os abstractions of processes and threads do not provide an api that is remotely object-orientedpython offers some really g...
3,654
absolute imports abstract base classes (abcs@classmethod about creating - using abstract factory pattern - abstraction about defining examples abstract methods access control adapter pattern about - adapter class interface interface aggregation about comparingwith composition assertion methods asyncio about asyncio fut...
3,655
about - closing exceptionraising log parsing - relationshipwith functions relationshipwith generators counter object coverage py data about defining objectsdefining data notation decorator pattern about core example - interface uses usingin python - decorators design patterns about - abstract factory pattern - adapter ...
3,656
information hiding about defining inheritance about - case study - instance diagram interfaces international standard book number (isbn iterator pattern case study - iterators about iterator protocol - javascript object notation (json lifo (last in first outqueues list comprehensions - lists about - sorting - mailing l...
3,657
url pick action pitfallsthreads about global interpreter lock shared memory polymorphism priority queue properties about using - usingfor adding behavior to class data - property constructor property function public interface creating py test about cleanup - setup - testing with - testsskipping with variablessetting up...
3,658
some examples of pytorch syntax the main oo concepts pre-defined and programmer-supplied attributes function objects vs callables defining class in python how python creates an instance defining methods creating class hierarchy multiple-inheritance class hierarchies making class instance iterable purdue university new(...
3,659
outline some examples of pytorch syntax the main oo concepts pre-defined and programmer-supplied attributes function objects vs callables defining class in python how python creates an instance defining methods creating class hierarchy multiple-inheritance class hierarchies making class instance iterable purdue univers...
3,660
some examples of pytorch syntax if you are not already well-schooled in the syntax of object-oriented pythonyou might find the following examples somewhat befuddlingimport torchvision transforms as tvt xform tvt compose[tvt grayscale(num_output_channels )tvt resize(( , )out_image xforminput_image_pil the statement in t...
3,661
some examples of pytorch syntax (contd now consider the following exampleclass encoderrnn(torch nn module)def __init__(selfinput_sizehidden_size)super(encoderrnnself__init__(==the rest of the definition ==we are obviously trying to define new class named encoderrnn as subclass of torch nn module and the method init (is...
3,662
some examples of pytorch syntax (contd for another examplethe two layers in the following neural network (from pytorch tutorialare declared in lines (aand (band how the network is connected is declared in forward(in line (cwe push data through the network by calling model(xin line (dbut we never call forward(how is one...
3,663
some examples of pytorch syntax (contd for another example that may confuse beginning python programmerconsider the following syntax for constructing data loader in pytorch scripttraining_data torchvision datasets cifar root=self dataroottrain=truedownload=truetransform=transform_traintrain_data_loader torch utils data...
3,664
some examples of pytorch syntax (contd (continued from previous slidefor novice python programmera construct like for in somethingto make sense"somethinngis likely to be one of the typical storage containerslike listtuplesetetc but 'train data loaderdoes not look like any of those storage containers so what' going on h...
3,665
outline some examples of pytorch syntax the main oo concepts pre-defined and programmer-supplied attributes function objects vs callables defining class in python how python creates an instance defining methods creating class hierarchy multiple-inheritance class hierarchies making class instance iterable purdue univers...
3,666
the main oo concepts the following fundamental notions of object-oriented programming in general apply to object-oriented python alsoclassinstancesand attributes encapsulation inheritance polymorphism purdue university
3,667
what are classes and instancesat high level of conceptualizationa class can be thought of as category we may think of "catas class specific cat would then be an instance of this class for the purpose of writing codea class is data structure with attributes an instance constructed from class will have specific values fo...
3,668
attributesmethodsinstance variablesand class variables method is function you invoke on an instance of the class or the class itself method that is invoked on an instance is sometimes called an instance method you can also invoke method directly on classin which case it is called class method or static method attribute...
3,669
encapsulation hiding or controlling access to the implementation-related attributes and the methods of class is called encapsulation with appropriate data encapsulationa class will present well-defined public interface for its clientsthe users of the class client should only access those data attributes and invoke thos...
3,670
inheritance and polymorphism inheritance in object-oriented code allows subclass to inherit some or all of the attributes and methods of its superclass(espolymorphism basically means that given category of objects can exhibit multiple identities at the same timein the sense that cat instance is not only of type catbut ...
3,671
polymorphism (contd as an example of polymorphismsuppose we declare list animals ['kitty''fido''tabby''quacker''spot'of catsdotsand duck -instances made from different classes in some animal hierarchy -and if we were to invoke method calculateiq(on this list of animals in the following fashion for item in animalsitem c...
3,672
regarding the previous example on polymorphism in many object-oriented languagesa method such as calculateiq(would need to be declared for the root class animal for the control loop shown on the previous slide to work properly all of the public methods and attributes defined for the root class would constitute the publ...
3,673
outline some examples of pytorch syntax the main oo concepts pre-defined and programmer-supplied attributes function objects vs callables defining class in python how python creates an instance defining methods creating class hierarchy multiple-inheritance class hierarchies making class instance iterable purdue univers...
3,674
attributespre-defined vs programmer-supplied class in python comes with certain pre-defined attributes the pre-defined attributes of class are not to be confused with the programmer-supplied attributes such as the class and instance variables and the programmer-supplied methods by the same tokenan instance constructed ...
3,675
attributespre-defined vs programmer-supplied (contd note that in python the word attribute is used to describe any propertyvariable or method that can be invoked with the dot operator on either the class or an instance constructed from class what have mentioned above is worthy of note in case you have previously run in...
3,676
pre-defined and programmer-supplied methods for class to define it formallya method is function that can be invoked on an object using the object-oriented call syntax that for python is of the form obj method()where obj may either be an instance of class or the class itself thereforethe pre-defined functions that can b...
3,677
outline some examples of pytorch syntax the main oo concepts pre-defined and programmer-supplied attributes function objects vs callables defining class in python how python creates an instance defining methods creating class hierarchy multiple-inheritance class hierarchies making class instance iterable purdue univers...
3,678
function objects vs callables function object can only be created with def statement on the other handa callable is any object that can be called like function for examplea class name can be called directly to yield an instance of class thereforea class name is callable an instance object can also be called directlywha...
3,679
in python'()is an operator -the function call operator you will see objects that may be called with or without the '()operator andwhen they are called with '()'there may or may not exist any arguments inside the parentheses for class with method foocalling just foo returns result different from what is returned by foo(...
3,680
an example of class with callable instances import random random seed( class class xdef __init__selfarr self arr arr def get_num(selfi)return self arr[idef __call__(self)return self arr end of class definition xobj xrandom sample(range( , ) print(xobj get_num( )print(xobj() [ if you execute this codeyou will see the ou...
3,681
the same example but with no def for call import random random seed( class class xdef __init__selfarr self arr arr def get_num(selfi)return self arr[idef __call__(self)return self arr end of class definition xobj xrandom sample(range( , ) print(xobj get_num( ) print(xobj()traceback (most recent call lastfile "usingcall...
3,682
outline some examples of pytorch syntax the main oo concepts pre-defined and programmer-supplied attributes function objects vs callables defining class in python how python creates an instance defining methods creating class hierarchy multiple-inheritance class hierarchies making class instance iterable purdue univers...
3,683
defining class in python 'll present the full definition of python class in stages 'll start with very simple example of class to make the reader familiar with the pre-defined init (method whose role is to initialize the instance returned by call to the constructor firsthere is the simplest possible definition of class...
3,684
defining class in python (contd here is class with user-supplied init (this method is automatically invoked to initialize the state of the instance returned by call to person()class person class persondef __init__(selfa_namean_age )self name a_name self age an_age end of class definition #test codea_person person"zapho...
3,685
pre-defined attributes for class being an object in its own rightevery python class comes equipped with the following pre-defined attributesname string name of the class doc documentation string for the class bases tuple of parent classes of the class dict module purdue university dictionary whose keys are the names of...
3,686
pre-defined attributes for an instance since every class instance is also an object in its own rightit also comes equipped with certain pre-defined attributes we will be particularly interested in the following twoclass string name of the class from which the instance was constructed dict dictionary whose keys are the ...
3,687
dict vs dir(as an alternative to invoking dict use the built-in global dir()as in on class nameone can also dirmyclass that returns list of all the attribute namesfor variables and for methodsfor the class (both directly defined for the class and inherited from class' superclassesif we had called "printdir(person)for t...
3,688
illustrating the values for system-supplied attributes class person class person" very simple classdef __init__(self,nam,yy )self name nam self age yy #-end of class definition -#test codea_person person("zaphod", print(a_person nameprint(a_person ageclass attributesprint(person __name__print(person __doc__print(person...
3,689
class definitionmore general syntax class myclass 'optional documentation stringclass_var class_var var def __init__selfvar default )'optional documentation stringattribute var rest_of_construction_init_suite def some_methodselfsome_parameters )'optional documentation stringmethod_code purdue university
3,690
class definitionmore general syntax (contd regarding the syntax shown on the previous slidenote the class variables class var and class var such variables exist on per-class basismeaning that they are static class variable can be given value in class definitionas shown for class var in generalthe header of init (may lo...
3,691
class definitionmore general syntax (cond if you do not provide class with its own init ()the system will provide the class with default init (you override the default definition by providing your own implementation for init (the syntax for user-defined method for class is the same as for stand-alone python functionsex...
3,692
the root class object all classes are subclassedeither directly or indirectly from the root class object the object class defines set of methods with default implementations that are inherited by all classes derived from object the list of attributes defined for the object class can be seen by printing out the list ret...
3,693
new(vs init(outline some examples of pytorch syntax the main oo concepts pre-defined and programmer-supplied attributes function objects vs callables defining class in python how python creates an instance defining methods creating class hierarchy multiple-inheritance class hierarchies making class instance iterable pu...
3,694
new(vs init(how python creates an instance from class python uses the following two-step procedure for constructing an instance from classstep the call to the constructor creates what may be referred to as generic instance from the class definition the generic instance' memory allocation is customized with the code in ...
3,695
new(vs init(creating an instance from class (contd the method new (is implicitly considered by python to be static method its first parameter is meant to be set equal to the name of the class whose instance is desired and it must return the instance created if class does not provide its own definition for new () search...
3,696
example showing new(vs init(new (and init (working together for instance creation the script shown on slide defines class and provides it with static method new (and an instance method init (we do not need any special declaration for new (to be recognized as static because this method is special-cased by python note th...
3,697
new(vs init(instance construction example (contd in the script on the next slidealso note that the namespace dictionary xobj dict created at runtime for the instance xobj is empty -for obvious reasons as stated earlierwhen dir(is called on classit returns list of all the attributes that can be invoked on class and on t...
3,698
new(vs init(instance construction example (contd class class (object)def __new__cls )print("__new__ invoked"return object __new__cls def __init__self )print("__init__ invoked" derived from root class object the param 'clsset to the name of the class test code xobj (printx __dict__ __new__ invoked __init__ invoked #{'__...
3,699
new(vs init(instance construction example (contd class class xx is still derived from the root class object def __new__cls )the param 'clsset to the name of the class print("__new__ invoked"return object __new__cls def __init__self )print("__init__ invoked"test code xobj (printx __dict__ printdir(xprintdirxobj purdue u...