id
int64
0
25.6k
text
stringlengths
0
4.59k
7,800
that will discuss matthew rocklin' multipledispatch as the best current implementation of the concept it implements most third-party libraries around functional programming are collections of higher-order functionsand sometimes enhancements to the tools for working lazily with iterators contained in itertools some notable examples include the followingbut this list should not be taken as exhaustivepyrsistent contains number of immutable collections all methods on data structure that would normally mutate it instead return new copy of the structure containing the requested updates the original structure is left untouched toolz provides set of utility functions for iteratorsfunctionsand dictionaries these functions interoperate well and form the building blocks of common data analytic operations they extend the standard libraries itertools and functools and borrow heavily from the standard libraries of contemporary functional languages hypothesis is library for creating unit tests for finding edge cases in your code you wouldn' have thought to look for it works by generating random data matching your specification and checking that your guarantee still holds in that case this is often called property-based testingand was popularized by the haskell library quickcheck more_itertools tries to collect useful compositions of iterators that neither itertools nor the recipes included in its docs address these compositions are deceptively tricky to get right and this well-crafted library helps users avoid pitfalls of rolling them themselves resources there are large number of other papersarticlesand books written about functional programmingin python and otherwise the python standard documentation itself contains an excellent introduction called "functional programming howto,by andrew kuchlingthat discusses some of the motivation for functional programming stylesas well as particular capabilities in python preface vii
7,801
domain articles this author wrote in the son which portions of this report are based these includethe first of my book text processing in pythonwhich discusses functional programming for text processingin the section titled "utilizing higher-order functions in text processing also wrote several articlesmentioned by kuchlingfor ibm' developerworks site that discussed using functional programming in an early version of python xcharming pythonfunctional programming in pythonpart making more out of your favorite scripting language charming pythonfunctional programming in pythonpart wading into functional programmingcharming pythonfunctional programming in pythonpart currying and other higher-order functions not mentioned by kuchlingand also for an older version of pythoni discussed multiple dispatch in another article for the same column the implementation created there has no advantages over the more recent multipledispatch librarybut it provides longer conceptual explanation than this report cancharming pythonmultiple dispatchgeneralizing polymorphism with multimethods stylistic note as in most programming textsa fixed font will be used both for inline and block samples of codeincluding simple command or function names within code blocksa notional segment of pseudocode is indicated with word surrounded by angle brackets ( not valid python)such as in other casessyntactically valid but undefined functions are used with descriptive namessuch as get_the_data(viii preface
7,802
in typical imperative python programs--including those that make use of classes and methods to hold their imperative code-- block of code generally consists of some outside loops (for or while)assignment of state variables within those loopsmodification of data structures like dictslistsand sets (or various other structureseither from the standard library or from third-party packages)and some branch statements (if/elif/else or try/except/finallyall of this is both natural and seems at first easy to reason about the problems often arisehoweverprecisely with those side effects that come with state variables and mutable data structuresthey often model our concepts from the physical world of containers fairly wellbut it is also difficult to reason accurately about what state data is in at given point in program one solution is to focus not on constructing data collection but rather on describing "whatthat data collection consists of when one simply thinks"here' some datawhat do need to do with it?rather than the mechanism of constructing the datamore direct reasoning is often possible the imperative flow control described in the last paragraph is much more about the "howthan the "whatand we can often shift the question encapsulation one obvious way of focusing more on "whatthan "howis simply to refactor codeand to put the data construction in more isolated place-- in function or method for exampleconsider an existing snippet of imperative code that looks like this
7,803
collection get_initial_state(state_var none for datum in data_setif condition(state_var)state_var calculate_from(datumnew modify(datumstate_varcollection add_to(newelsenew modify_differently(datumcollection add_to(newnow actually work with the data for thing in collectionprocess(thingwe might simply remove the "howof the data construction from the current scopeand tuck it away in function that we can think about in isolation (or not think about at all once it is sufficiently abstractedfor exampletuck away construction of data def make_collection(data_set)collection get_initial_state(state_var none for datum in data_setif condition(state_var)state_var calculate_from(datumstate_varnew modify(datumstate_varcollection add_to(newelsenew modify_differently(datumcollection add_to(newreturn collection now actually work with the data for thing in make_collection(data_set)process(thingwe haven' changed the programming logicnor even the lines of codeat allbut we have still shifted the focus from "how do we construct collection?to "what does make_collection(create?comprehensions using comprehensions is often way both to make code more compact and to shift our focus from the "howto the "what comprehension is an expression that uses the same keywords as loop and conditional blocksbut inverts their order to focus on the data (avoidingflow control
7,804
sion can often make surprisingly large difference in how we reason about code and how easy it is to understand the ternary operator also performs similar restructuring of our focususing the same keywords in different order for exampleif our original code wascollection list(for datum in data_setif condition(datum)collection append(datumelsenew modify(datumcollection append(newsomewhat more compactly we could write this ascollection [ if condition(delse modify(dfor in data_setfar more important than simply saving few characters and lines is the mental shift enacted by thinking of what collection isand by avoiding needing to think about or debug "what is the state of col lection at this point in the loop?list comprehensions have been in python the longestand are in some ways the simplest we now also have generator comprehensionsset comprehensionsand dict comprehensions available in python syntax as caveat thoughwhile you can nest comprehensions to arbitrary depthpast fairly simple level they tend to stop clarifying and start obscuring for genuinely complex construction of data collectionrefactoring into functions remains more readable generators generator comprehensions have the same syntax as list comprehensions--other than that there are no square brackets around them (but parentheses are needed syntactically in some contextsin place of brackets)--but they are also lazy that is to say that they are merely description of "how to get the datathat is not realized until one explicitly asks for iteither by calling next(on the objector by looping over it this often saves memory for large sequences and defers computation until it is actually needed for examplelog_lines (line for line in read_line(huge_log_fileif complex_condition(line)comprehensions
7,805
listbut runtime behavior is nicer obviouslythis generator comprehension also has imperative versionsfor exampledef get_log_lines(log_file)line read_line(log_filewhile truetryif complex_condition(line)yield line line read_line(log_fileexcept stopiterationraise log_lines get_log_lines(huge_log_fileyesthe imperative version could be simplified toobut the version shown is meant to illustrate the behind-the-scenes "howof for loop over an iteratable--more details we also want to abstract from in our thinking in facteven using yield is somewhat of an abstraction from the underlying "iterator protocol we could do this with class that had __next__(and __iter__(methods for exampleclass getloglines(object)def __init__(selflog_file)self log_file log_file self line none def __iter__(self)return self def __next__(self)if self line is noneself line read_line(log_filewhile not complex_condition(self line)self line read_line(self log_filereturn self line log_lines getloglines(huge_log_fileaside from the digression into the iterator protocol and laziness more generallythe reader should see that the comprehension focuses attention much better on the "what,whereas the imperative version--although successful as refactorings perhaps--retains the focus on the "how dicts and sets in the same fashion that lists can be created in comprehensions rather than by creating an empty listloopingand repeatedly call (avoidingflow control
7,806
rather than by repeatedly calling update(or add(in loop for example{ :chr( +ifor in range( ){ ' ' ' ' ' ' ' ' ' ' ' '{chr( +ifor in range( ){' '' '' '' '' '' 'the imperative versions of these comprehensions would look very similar to the examples shown earlier for other built-in datatypes recursion functional programmers often put weight in expressing flow control through recursion rather than through loops done this waywe can avoid altering the state of any variables or data structures within an algorithmand more importantly get more at the "whatthan the "howof computation howeverin considering using recursive styles we should distinguish between the cases where recursion is just "iteration by another nameand those where problem can readily be partitioned into smaller problemseach approached in similar way there are two reasons why we should make the distinction mentioned on the one handusing recursion effectively as way of marching through sequence of elements iswhile possiblereally not "pythonic it matches the style of other languages like lispdefinitelybut it often feels contrived in python on the other handpython is simply comparatively slow at recursionand has limited stack depth limit yesyou can change this with sys setrecursion limit(to more than the default but if you find yourself doing so it is probably mistake python lacks an internal feature called tail call elimination that makes deep recursion computationally efficient in some languages let us find trivial example where recursion is really just kind of iterationdef running_sum(numbersstart= )if len(numbers= print(return total numbers[ start print(totalend="running_sum(numbers[ :]totalrecursion
7,807
that simply repeatedly modified the total state variable would be more readableand moreover this function is perfectly reasonable to want to call against sequences of much larger length than howeverin other casesrecursive styleeven over sequential operationsstill expresses algorithms more intuitively and in way that is easier to reason about slightly less trivial examplefactorial in recursive and iterative styledef factorialr( )"recursive factorial functionassert isinstance(nintand > return if < else factorialr( - def factoriali( )"iterative factorial functionassert isinstance(nintand > product while > product * - return product although this algorithm can also be expressed easily enough with running product variablethe recursive expression still comes closer to the "whatthan the "howof the algorithm the details of repeatedly changing the values of product and in the iterative version feels like it' just bookkeepingnot the nature of the computation itself (but the iterative version is probably fasterand it is easy to reach the recursion limit if it is not adjustedas footnotethe fastest version know of for factorial(in python is in functional programming styleand also expresses the "whatof the algorithm well once some higher-order functions are familiarfrom functools import reduce from operator import mul def factorialhof( )return reduce(mulrange( + ) where recursion is compellingand sometimes even the only really obvious way to express solutionis when problem offers itself to "divide and conquerapproach that isif we can do similar computation on two halves (or anywayseveral similarly sized chunksof larger collection in that casethe recursion depth is only (log nof the size of the collectionwhich is unlikely to be (avoidingflow control
7,808
expressed without any state variables or loopsbut wholly through recursiondef quicksort(lst)"quicksort over list-like sequenceif len(lst= return lst pivot lst[ pivots [ for in lst if =pivotsmall quicksort([ for in lst if pivot]large quicksort([ for in lst if pivot]return small pivots large some names are used in the function body to hold convenient valuesbut they are never mutated it would not be as readablebut the definition could be written as single expression if we wanted to do so in factit is somewhat difficultand certainly less intuitiveto transform this into stateful iterative version as general adviceit is good practice to look for possibilities of recursive expression--and especially for versions that avoid the need for state variables or mutable data collections--whenever problem looks partitionable into smaller problems it is not good idea in python--most of the time--to use recursion merely for "iteration by other means eliminating loops just for funlet us take quick look at how we could take out all loops from any python program most of the time this is bad ideaboth for readability and performancebut it is worth looking at how simple it is to do in systematic fashion as background to contemplate those cases where it is actually good idea if we simply call function inside for loopthe built-in higherorder function map(comes to our aidfor in itfunc(estatement-based loop the following code is entirely equivalent to the functional versionexcept there is no repeated rebinding of the variable involvedand hence no statemap(funcitmap()-based "loopeliminating loops
7,809
tial program flow most imperative programming consists of statements that amount to "do thisthen do thatthen do the other thing if those individual actions are wrapped in functionsmap(lets us do just thislet (etcbe functions that perform actions an execution utility function do_it lambda *argsf(*argsmap()-based action sequence map(do_it[ ]we can combine the sequencing of function calls with passing arguments from iterableshello lambda firstlastprint("hello"firstlastbye lambda firstlastprint("bye"firstlast_ list(map(do_it[hellobye]['david','jane']['mertz','doe'])hello david mertz bye jane doe of courselooking at the exampleone suspects the result one really wants is actually to pass all the arguments to each of the functions rather than one argument from each list to each function expressing that is difficult without using list comprehensionbut easy enough using onedo_all_funcs lambda fns*argslist(map(fn*args)for fn in fns_ do_all_funcs([hellobye]['david','jane']['mertz','doe']hello david mertz hello jane doe bye david mertz bye jane doe in generalthe whole of our main program couldin principlebe map(expression with an iterable of functions to execute to complete the program translating while is slightly more complicatedbut is possible to do directly using recursionstatement-based while loop while if break else (avoidingflow control
7,810
fp-style recursive while loop def while_block()if return elsereturn while_fp lambdaand while_block()or while_fp(while_fp(our translation of while still requires while_block(function that may itself contain statements rather than just expressions we could go further in turning suites into function sequencesusing map(as above if we did thiswe couldmoreoveralso return single ternary expression the details of this further purely functional refactoring is left to readers as an exercise (hintit will be uglyfun to play withbut not good production codeit is hard for to be useful with the usual testssuch as while myvar== since the loop body (by designcannot change any variable values one way to add more useful condition is to let while_block(return more interesting valueand compare that return value for termination condition here is concrete example of eliminating statementsimperative version of "echo()def echo_imp()while input("imp -"if ='quit'break elseprint(xecho_imp(now let' remove the while loop for the functional versionfp version of "echo()def identity_print( )"identity with side-effectprint(xreturn echo_fp lambdaidentity_print(input("fp -"))=='quitor echo_fp(echo_fp(eliminating loops
7,811
little program that involves /oloopingand conditional statements as pure expression with recursion (in factas function object that can be passed elsewhere if desiredwe do still utilize the utility function identity_print()but this function is completely generaland can be reused in every functional program expression we might create later (it' one-time costnotice that any expression containing identity_print(xevaluates to the same thing as if it had simply contained xit is only called for its / side effect eliminating recursion as with the simple factorial example given abovesometimes we can perform "recursion without recursionby using func tools reduce(or other folding operations (other "foldsare not in the python standard librarybut can easily be constructed and/or occur in third-party librariesa recursion is often simply way of combining something simpler with an accumulated intermediate resultand that is exactly what reduce(does at heart slightly longer discussion of functools reduce(occurs in the on higher-order functions (avoidingflow control
7,812
the emphasis in functional programming issomewhat tautologouslyon calling functions python actually gives us several different ways to create functionsor at least something very function-like ( that can be calledthey areregular functions created with def and given name at definition time anonymous functions created with lambda instances of classes that define __call()__ method closures returned by function factories static methods of instanceseither via the @staticmethod decorator or via the class __dict__ generator functions this list is probably not exhaustivebut it gives sense of the numerous slightly different ways one can create something callable of coursea plain method of class instance is also callablebut one generally uses those where the emphasis is on accessing and modifying mutable state python is multiple paradigm languagebut it has an emphasis on object-oriented styles when one defines classit is generally to generate instances meant as containers for data that change as one calls methods of the class this style is in some ways opposite to functional programming approachwhich emphasizes immutability and pure functions
7,813
determine what result to return is not pure function of courseall the other types of callables we discuss also allow reliance on state in various ways the author of this report has long pondered whether he could use some dark magic within python explicitly to declare function as pure--say by decorating it with hypothetical @purefunction decorator that would raise an exception if the function can have side effects--but consensus seems to be that it would be impossible to guard against every edge case in python' internal machinery the advantage of pure function and side-effect-free code is that it is generally easier to debug and test callables that freely intersperse statefulness with their returned results cannot be examined independently of their running context to see how they behaveat least not entirely so for examplea unit test (using doctest or unittestor some third-party testing framework such as py test or nosemight succeed in one context but fail when identical calls are made within runningstateful program of courseat the very leastany program that does anything must have some kind of output (whether to consolea filea databaseover the networkor whateverin it to do anything usefulso side effects cannot be entirely eliminatedonly isolated to degree when thinking in functional programming terms named functions and lambdas the most obvious ways to create callables in python arein definite order of obviousnessnamed functions and lambdas the only inprinciple difference between them is simply whether they have __qualname__ attributesince both can very well be bound to one or more names in most caseslambda expressions are used within python only for callbacks and other uses where simple action is inlined into function call but as we have shown in this reportflow control in general can be incorporated into single-expression lambdas if we really want let' define simple example to illustratedef hello (name)print("hello"namehello lambda nameprint("hello"namehello ('david'hello david callables
7,814
hello david hello __qualname__ 'hello hello __qualname__ 'hello hello can bind func to other names hello __qualname__ 'hello __qualname__ 'hello hello __qualname__ 'hello one of the reasons that functions are useful is that they isolate state lexicallyand avoid contamination of enclosing namespaces this is limited form of nonmutability in that (by defaultnothing you do within function will bind state variables outside the function of coursethis guarantee is very limited in that both the global and nonlocal statements explicitly allow state to "leak outof function moreovermany data types are themselves mutableso if they are passed into function that function might change their contents furthermoredoing / can also change the "state of the worldand hence alter results of functions ( by changing the contents of file or database that is itself read elsewherenotwithstanding all the caveats and limits mentioned abovea programmer who wants to focus on functional programming style can intentionally decide to write many functions as pure functions to allow mathematical and formal reasoning about them in most casesone only leaks state intentionallyand creating certain subset of all your functionality as pure functions allows for cleaner code they might perhaps be broken up by "puremodulesor annotated in the function names or docstrings closures and callable instances there is saying in computer science that class is "data with operations attachedwhile closure is "operations with data attached in some sense they accomplish much the same thing of putting logic and data in the same object but there is definitely philosophical difference in the approacheswith classes emphasizing mutable or rebindable stateand closures emphasizing immutability and pure functions neither side of this divide is absolute--at least in python --but different attitudes motivate the use of each closures and callable instances
7,815
"hello worldof the different stylesa class that creates callable adder instances class adder(object)def __init__(selfn)self def __call__(selfm)return self add _i adder( "instanceor "imperativewe have constructed something callable that adds five to an argument passed in seems simple and mathematical enough let us also try it as closuredef make_adder( )def adder( )return return adder add _f make_adder( "functionalso far these seem to amount to pretty much the same thingbut the mutable state in the instance provides attractive nuisanceadd _i( add _f( add _i add _i( only argument affects result state is readily changeable result is dependent on prior flow the behavior of an "addercreated by either adder(or make_adder(isof coursenot determined until runtime in general but once the object existsthe closure behaves in pure functional waywhile the class instance remains state dependent one might simply settle for "don' change that state"--and indeed that is possible (if no one else with poorer understanding imports and uses your code)--but one is accustomed to changing the state of instancesand style that prevents abuse programmatically encourages better habits there is little "gotchaabout how python binds variables in closures it does so by name rather than valueand that can cause confusionbut also has an easy solution for examplewhat if we want to manufacture several related closures encapsulating different data callables
7,816
adders [for in range( )adders append(lambda mm+ [adder( for adder in adders[ [adder( for adder in adders[ fortunatelya small change brings behavior that probably better meets our goaladders [for in range( )adders append(lambda mn=nm+ [adder( for adder in adders[ [adder( for adder in adders[ add adders[ add ( can override the bound value notice that using the keyword argument scope-binding trick allows you to change the closed-over valuebut this poses much less of danger for confusion than in the class instance the overriding value for the named variable must be passed explictly in the call itselfnot rebound somewhere remote in the program flow yesthe name add is no longer accurately descriptive for "add any two numbers,but at least the change in result is syntactically local methods of classes all methods of classes are callables for the most parthowevercalling method of an instance goes against the grain of functional programming styles usually we use methods because we want to reference mutable data that is bundled in the attributes of the instanceand hence each call to method may produce different result that varies independently of the arguments passed to it accessors and operators even accessorswhether created with the @property decorator or otherwiseare technically callablesalbeit accessors are callables with methods of classes
7,817
they take no arguments as gettersand return no value as settersclass car(object)def __init__(self)self _speed @property def speed(self)print("speed is"self _speedreturn self _speed @speed setter def speed(selfvalue)print("setting to"valueself _speed value >car car(car speed setting to car speed speed is odd syntax to pass one argument in an accessorwe co-opt the python syntax of assignment to pass an argument instead that in itself is fairly easy for much python syntax thoughfor exampleclass talkativeint(int)def __lshift__(selfother)print("shift"self"by"otherreturn int __lshift__(selfothert talkativeint( < shift by every operator in python is basically method call "under the hood but while occasionally producing more readable "domain specific language(dsl)defining special callable meanings for operators adds no improvement to the underlying capabilities of function calls static methods of instances one use of classes and their methods that is more closely aligned with functional style of programming is to use them simply as namespaces to hold variety of related functions callables
7,818
class righttriangle(object)"class used solely as namespace for related functions@staticmethod def hypotenuse(ab)return math sqrt( ** ** @staticmethod def sin(ab)return righttriangle hypotenuse(ab@staticmethod def cos(ab)return righttriangle hypotenuse(abkeeping this functionality in class avoids polluting the global (or moduleetc namespaceand lets us name either the class or an instance of it when we make calls to pure functions for examplerighttriangle hypotenuse( , rt righttriangle(rt sin( , rt cos( , by far the most straightforward way to define static methods is with the decorator named in the obvious way howeverin python xyou can pull out functions that have not been so decorated too-- the concept of an "unbound methodis no longer needed in modern python versionsimport functoolsoperator class math(object)def product(*nums)return functools reduce(operator mulnumsdef power_chain(*nums)return functools reduce(operator pownumsmath product( , , math power_chain( , , without @staticmethodhoweverthis will not work on the instances since they still expect to be passed selfm math( product( , , methods of classes
7,819
traceback (most recent call lastin (---- product( , , in product(*nums class math(object) def product(*nums)---- return functools reduce(operator mulnums def power_chain(*nums) return functools reduce(operator pownumstypeerrorunsupported operand type(sfor *'mathand 'intif your namespace is entirely bag for pure functionsthere is no reason not to call via the class rather than the instance but if you wish to mix some pure functions with some other stateful methods that rely on instance mutable stateyou should use the @staticme thod decorator generator functions special sort of function in python is one that contains yield statementwhich turns it into generator what is returned from calling such function is not regular valuebut rather an iterator that produces sequence of values as you call the next(function on it or loop over it this is discussed in more detail in the entitled "lazy evaluation while like any python objectthere are many ways to introduce statefulness into generatorin principle generator can be "purein the sense of pure function it is merely pure function that produces (potentially infinitesequence of values rather than single valuebut still based only on the arguments passed into it noticehoweverthat generator functions typically have great deal of internal stateit is at the boundaries of call signature and return value that they act like side-effect-free "black box simple exampledef get_primes()"simple lazy sieve of eratosthenescandidate found [while trueif all(candidate prime ! for prime in found)yield candidate found append(candidatecandidate + callables
7,820
primes get_primes(next(primes)next(primes)next(primes( for _prime in zip(range( )primes)print(primeend=" every time you create new object with get_primes(the iterator is the same infinite lazy sequence--another example might pass in some initializing values that affected the result--but the object itself is stateful as it is consumed incrementally multiple dispatch very interesting approach to programming multiple paths of execution is technique called "multiple dispatchor sometimes "multimethods the idea here is to declare multiple signatures for single function and call the actual computation that matches the types or properties of the calling arguments this technique often allows one to avoid or reduce the use of explicitly conditional branchingand instead substitute the use of more intuitive pattern descriptions of arguments long time agothis author wrote module called multimethods that was quite flexible in its options for resolving "dispatch linearizationbut is also so old as only to work with python xand was even written before python had decorators for more elegant expression of the concept matthew rocklin' more recent multipledis patch is modern approach for recent python versionsalbeit it lacks some of the theoretical arcana explored in my ancient module ideallyin this author' opiniona future python version would include standardized syntax or api for multiple dispatch (but more likely the task will always be the domain of third-party librariesto explain how multiple dispatch can make more readable and less bug-prone codelet us implement the game of rock/paper/scissors in three styles let us create the classes to play the game for all the versionsclass thing(object)pass class rock(thing)pass multiple dispatch
7,821
class scissors(thing)pass many branches first purely imperative version this is going to have lot of repetitivenestedconditional blocks that are easy to get wrongdef beats(xy)if isinstance(xrock)if isinstance(yrock)return none no winner elif isinstance(ypaper)return elif isinstance(yscissors)return elseraise typeerror("unknown second thing"elif isinstance(xpaper)if isinstance(yrock)return elif isinstance(ypaper)return none no winner elif isinstance(yscissors)return elseraise typeerror("unknown second thing"elif isinstance(xscissors)if isinstance(yrock)return elif isinstance(ypaper)return elif isinstance(yscissors)return none no winner elseraise typeerror("unknown second thing"elseraise typeerror("unknown first thing"rockpaperscissors rock()paper()scissors(beats(paperrockbeats(paper typeerrorunknown second thing delegating to the object as second try we might try to eliminate some of the fragile repitition with python' "duck typing"--that ismaybe we can have different things share common method that is called as needed callables
7,822
def beats(selfother)if isinstance(otherrock)return none no winner elif isinstance(otherpaper)return other elif isinstance(otherscissors)return self elseraise typeerror("unknown second thing"class duckpaper(paper)def beats(selfother)if isinstance(otherrock)return self elif isinstance(otherpaper)return none no winner elif isinstance(otherscissors)return other elseraise typeerror("unknown second thing"class duckscissors(scissors)def beats(selfother)if isinstance(otherrock)return other elif isinstance(otherpaper)return self elif isinstance(otherscissors)return none no winner elseraise typeerror("unknown second thing"def beats (xy)if hasattr( 'beats')return beats(yelseraise typeerror("unknown first thing"rockpaperscissors duckrock()duckpaper()duckscissors(beats (rockpaperbeats ( rocktypeerrorunknown first thing we haven' actually reduced the amount of codebut this version somewhat reduces the complexity within each individual callableand reduces the level of nested conditionals by one most of the logic is pushed into separate classes rather than deep branching in multiple dispatch
7,823
object(but only to the one controlling objectpattern matching as final trywe can express all the logic more directly using multiple dispatch this should be more readablealbeit there are still number of cases to definefrom multipledispatch import dispatch @dispatch(rockrockdef beats (xy)return none @dispatch(rockpaperdef beats (xy)return @dispatch(rockscissorsdef beats (xy)return @dispatch(paperrockdef beats (xy)return @dispatch(paperpaperdef beats (xy)return none @dispatch(paperscissorsdef beats (xy)return @dispatch(scissorsrockdef beats (xy)return @dispatch(scissorspaperdef beats (xy)return @dispatch(scissorsscissorsdef beats (xy)return none @dispatch(objectobjectdef beats (xy)if not isinstance( (rockpaperscissors))raise typeerror("unknown first thing"elseraise typeerror("unknown second thing"beats (rockpaperbeats (rock typeerrorunknown second thing callables
7,824
really exotic approach to expressing conditionals as dispatch decisions is to include predicates directly within the function signatures (or perhaps within decorators on themas with multipledispatchi do not know of any well-maintained python library that does thisbut let us simply stipulate hypothetical library briefly to illustrate the concept this imaginary library might be aptly named predicative_dispatchfrom predicative_dispatch import predicate @predicate(lambda xx lambda ytruedef sign(xy)print(" is negativey is" @predicate(lambda xx = lambda ytruedef sign(xy)print(" is zeroy is" @predicate(lambda xx lambda ytruedef sign(xy)print(" is positivey is"ywhile this small example is obviously not full specificationthe reader can see how we might move much or all of the conditional branching into the function call signatures themselvesand this might result in smallermore easily understood and debugged functions multiple dispatch
7,825
powerful feature of python is its iterator protocol (which we will get to shortlythis capability is only loosely connected to functional programming per sesince python does not quite offer lazy data structures in the sense of language like haskell howeveruse of the iterator protocol--and python' many built-in or standard library iteratables--accomplish much the same effect as an actual lazy data structure let us explain the contrast here in slightly more detail in language like haskellwhich is inherently lazily evaluatedwe might define list of all the prime numbers in manner like the following-define list of all the prime numbers primes sieve [ where sieve ( :xsp sieve [ <xs( `remp)/= this report is not the place to try to teach haskellbut you can see comprehension in therewhich is in fact the model that python used in introducing its own comprehensions there is also deep recursion involvedwhich is not going to work in python apart from syntactic differencesor even the ability to recurse to indefinite depththe significant difference here is that the haskell version of primes is an actual (infinitesequencenot just an object capable of sequentially producing elements (as was the primes object we demonstrated in the entitled "callables"in particularyou can index into an arbitrary element of the infinite list of primes in haskelland the intermediate values will be produced internally as needed based on the syntactic construction of the list itself
7,826
inherent syntax of the language and takes more manual construction given the get_primes(generator function discussed earlierwe might write our own container to simulate the same thingfor examplefrom collections abc import sequence class expandingsequence(sequence)def __init__(selfit)self it it self _cache [def __getitem__(selfindex)while len(self _cache<indexself _cache append(next(self it)return self _cache[indexdef __len__(self)return len(self _cachethis new container can be both lazy and also indexibleprimes expandingsequence(get_primes()for _p in zip(range( )primes)print(pend=" primes[ primes[ len(primes primes[ len(primes of coursethere are other custom capabilities we might want to engineer insince lazy data structures are not inherently intertwined into python maybe we' like to be able to slice this special sequence maybe we' like prettier representation of the object when printed maybe we should report the length as inf if we somehow signaled it was meant to be infinite all of this is possiblebut it takes little bit of code to add each behavior rather than simply being the default assumption of python data structures lazy evaluation
7,827
the easiest way to create an iterator--that is to saya lazy sequence --in python is to define generator functionas was discussed in the entitled "callables simply use the yield statement within the body of function to define the places (usually in loopwhere values are produced ortechnicallythe easiest way is to use one of the many iterable objects already produced by built-ins or the standard library rather than programming custom one at all generator functions are syntax sugar for defining function that returns an iterator many objects have method named __iter__()which will return an iterator when it is calledgenerally via the iter(built-in functionor even more often simply by looping over the object ( for item in collectionwhat an iterator is is the object returned by call to iter(some thing)which itself has method named __iter__(that simply returns the object itselfand another method named __next__(the reason the iterable itself still has an __iter__(method is to make iter(idempotent that isthis identity should always hold (or raise typeerror("object is not iterable"))iter_seq iter(sequenceiter(iter_seq=iter_seq the above remarks are bit abstractso let us look at few concrete exampleslazy open(' -laziness md'iterate over lines of file '__iter__in dir(lazyand '__next__in dir(lazytrue plus map(lambda xx+ range( )plus iterate over deferred computations '__iter__in dir(plus and '__next__in dir(plus true def to ()for in range( )yield '__iter__in dir(to false '__iter__in dir(to ()and '__next__in dir(to ()true the iterator protocol
7,828
'__iter__in dir(ltrue '__next__in dir(lfalse li iter(literate over concrete collection li li =iter(litrue in functional programming style--or even just generally for readability--writing custom iterators as generator functions is most natural howeverwe can also create custom classes that obey the protocoloften these will have other behaviors ( methodsas wellbut most such behaviors necessarily rely on statefulness and side effects to be meaningful for examplefrom collections abc import iterable class fibonacci(iterable)def __init__(self)self aself self total def __iter__(self)return self def __next__(self)self aself self bself self self total +self return self def running_sum(self)return self total fib fibonacci(fib running_sum( for _i in zip(range( )fib)print(iend=" fib running_sum( next(fib this example is trivialof coursebut it shows class that both implements the iterator protocol and also provides an additional method to return something stateful about its instance since statefulness is for object-oriented programmersin functional programming style we will generally avoid classes like this lazy evaluation
7,829
the module itertools is collection of very powerful--and carefully designed--functions for performing iterator algebra that isthese allow you to combine iterators in sophisticated ways without having to concretely instantiate anything more than is currently required as well as the basic functions in the module itselfthe module documentation provides number of shortbut easy to get subtly wrongrecipes for additional functions that each utilize two or three of the basic functions in combination the third-party module more_itertools mentioned in the preface provides additional functions that are likewise designed to avoid common pitfalls and edge cases the basic goal of using the building blocks inside itertools is to avoid performing computations before they are requiredto avoid the memory requirements of large instantiated collectionto avoid potentially slow / until it is stricly requiredand so on iterators are lazy sequences rather than realized collectionsand when combined with functions or recipes in itertools they retain this property here is quick example of combining few things rather than the stateful fibonacci class to let us keep running sumwe might simply create single lazy iterator to generate both the current number and this sumdef fibonacci()ab while trueyield ab ba+ from itertools import teeaccumulate st tee(fibonacci()pairs zip(taccumulate( )for (fibtotalin zip(range( )pairs)print(fibtotal moduleitertools
7,830
and optimally often requires careful thoughtbut once combinedremarkable power is obtained for dealing with largeor even infiniteiterators that could not be done with concrete collections the documentation for the itertools module contain details on its combinatorial functions as well as number of short recipes for combining them this paper does not have space to repeat those descriptionsso just exhibiting few of them above will suffice note that for practical purposeszip()map()filter()and range((which isin sensejust terminating itertools count()could well live in itertools if they were not built-ins that isall of those functions lazily generate sequential items (mostly based on existing iterableswithout creating concrete sequence built-ins like all()any()sum()min()max()and functools reduce(also act on iterablesbut all of themin the general caseneed to exhaust the iterator rather than remain lazy the function itertools prod uct(might be out of place in its module since it also creates concrete cached sequencesand cannot operate on infinite iterators chaining iterables the itertools chain(and itertools chain from_iterable(functions combine multiple iterables built-in zip(and iter tools zip_longest(also do thisof coursebut in manners that allow incremental advancement through the iterables consequence of this is that while chaining infinite iterables is valid syntactically and semanticallyno actual program will exhaust the earlier iterable for examplefrom itertools import chaincount thrice_to_inf chain(count()count()count()conceptuallythrice_to_inf will count to infinity three timesbut in practice once would always be enough howeverfor merely large iterables--not for infinite ones--chaining can be very useful and parsimoniousdef from_logs(fnames)yield from (open(filefor file in fnameslines chain from_iterable(from_logs['huge log''gigantic log']) lazy evaluation
7,831
concrete list of files--that sequence of filenames itself could be lazy iterable per the api given besides the chaining with itertoolswe should mention collec tions chainmap(in the same breath dictionaries (or generally any collections abc mappingare iterable (over their keysjust as we might want to chain multiple sequence-like iterableswe sometimes want to chain together multiple mappings without needing to create single larger concrete one chainmap(is handyand does not alter the underlying mappings used to construct it moduleitertools
7,832
in the last we saw an iterator algebra that builds on the iter tools module in some wayshigher-order functions (often abbreviated as "hofs"provide similar building blocks to express complex concepts by combining simpler functions into new functions in generala higher-order function is simply function that takes one or more functions as arguments and/or produces function as result many interesting abstractions are available here they allow chaining and combining higher-order functions in manner analogous to how we can combine functions in itertools to produce new iterables few useful higher-order functions are contained in the functools moduleand few others are built-ins it is common the think of map()filter()and functools reduce(as the most basic building blocks of higher-order functionsand most functional programming languages use these functions as their primitives (occasionally under other namesalmost as basic as map/filter/reduce as building block is currying in pythoncurrying is spelled as partial()and is contained in the functools module--this is function that will take another functionalong with zero or more arguments to pre-filland return function of fewer arguments that operates as the input function would when those arguments are passed to it the built-in functions map(and filter(are equivalent to comprehensions--especially now that generator comprehensions are available--and most python programmers find the comprehension versions more readable for examplehere are some (almostequivalent pairs
7,833
transformed map(tranformationiteratorcomprehension transformed (transformation(xfor in iteratorclassic "fp-stylefiltered filter(predicateiteratorcomprehension filtered ( for in iterator if predicate( )the function functools reduce(is very generalvery powerfuland very subtle to use to its full power it takes successive items of an iterableand combines them in some way the most common use case for reduce(is probably covered by the built-in sum()which is more compact spelling offrom functools import reduce total reduce(operator addit total sum(itit may or may not be obvious that map(and filter(are also special cases of reduce(that isadd lambda nn+ reduce(lambda lxl+[add ( )]range( )[][ simplermap(add range( )isodd lambda nn% reduce(lambda lxl+[xif isodd(xelse lrange( )[][ simplerfilter(isoddrange( )these reduce(expressions are awkwardbut they also illustrate how powerful the function is in its generalityanything that can be computed from sequence of successive elements can (if awkwardlybe expressed as reduction there are few common higher-order functions that are not among the "batteries includedwith pythonbut that are very easy to create as utilities (and are included with many third-party collections of functional programming toolsdifferent libraries--and other programming languages--may use different names for the utility functions describebut analogous capabilities are widespread (as are the names choose higher-order functions
7,834
handy utility is compose(this is function that takes sequence of functions and returns function that represents the application of each of these argument functions to data argumentdef compose(*funcs)"""return new function compose( , )( = ( ( )))""def inner(datafuncs=funcs)result data for in reversed(funcs)result (resultreturn result return inner times lambda xx* minus lambda xx- mod lambda xx% compose(mod times minus all( ( )==(( - )* )% for in range( )true for these one-line math operations (times minus etc )we could have simply written the underlying math expression at least as easilybut if the composite calculations each involved branchingflow controlcomplex logicetc this would not be true the built-in functions all(and any(are useful for asking whether predicate holds of elements of an iterable but it is also nice to be able to ask whether any/all of collection of predicates hold for particular data item in composable way we might implement these asall_pred lambda item*testsall( (itemfor in testsany_pred lambda item*testsany( (itemfor in teststo show the uselet us make few predicatesis_lt partial(operator ge less than is_gt partial(operator le greater than from nums import is_prime implemented elsewhere all_pred( is_lt is_gt is_primetrue predicates (is_lt is_gt is_primeall_pred( *predicatesfalse the library toolz has what might be more general version of this called juxt(that creates function that calls several functions with utility higher-order functions
7,835
thatfor exampleto dofrom toolz functoolz import juxt juxt([is_lt is_gt is_prime])( (truetruetrueall(juxt([is_lt is_gt is_prime])( )true juxt([is_lt is_gt is_prime])( (falsetruetruethe utility higher-order functions shown here are just small selection to illustrate composability look at longer text on functional programming--orfor exampleread the haskell prelude--for many other ideas on useful utility higher-order-functions the operator module as has been shown in few of the examplesevery operation that can be done with python' infix and prefix operators corresponds to named function in the operator module for places where you want to be able to pass function performing the equivalent of some syntactic operation to some higher-order functionusing the name from operator is faster and looks nicer than corresponding lambda for examplecompare ad hoc lambda with `operatorfunction sum reduce(lambda aba+biterable sum reduce(operator additerable sum sum(iterablethe actual pythonic way the functools module the obvious place for python to include higher-order functions is in the functools moduleand indeed few are in there howeverthere are surprisingly few utility higher-order functions in that module it has gained few interesting ones over python versionsbut core developers have resistence to going in the direction of full functional programming language on the other handas we have seen in few example abovemany of the most useful higherorder functions only take few lines (sometimes single lineto write yourself apart from reduce()which is discussed at the start of this the main facility in the module is partial()which has also been higher-order functions
7,836
in many languages there are also some examples of using par tial(discussed above the remainder of the functools module is generally devoted to useful decoratorswhich is the topic of the next section decorators although it is--by design--easy to forget itprobably the most common use of higher-order functions in python is as decorators decorator is just syntax sugar that takes function as an argumentand if it is programmed correctlyreturns new function that is in some way an enhancement of the original function (or methodor classjust to remind readersthese two snippets of code defining some_func and other_func are equivalent@enhanced def some_func(*args)pass def other_func(*args)pass other_func enhanced(other_funcused with the decorator syntaxof coursethe higher-order function is necessarily used at definition time for function for their intended purposethis is usually when they are best applied but the same decorator function can alwaysin principlebe used elsewhere in programfor example in more dynamic way ( mapping decorator function across runtime-generated collection of other functionsthat would be an unusual use casehowever decorators are used in many places in the standard library and in common third-party libraries in some ways they tie in with an idea that used to be called "aspect-oriented programming for examplethe decorator function asyncio coroutine is used to mark function as coroutine within functools the three important decorator functions are functools lru_cachefunctools total_orderingand functools wraps the first "memoizesa function ( it caches the arguments passed and returns stored values rather than performing new computation or /othe second makes it easier to write custom classes that want to use inequality operators the last makes it easier to write new decorators all of these are important decorators
7,837
what is codingthere' been lot of discussion around coding latelybut it can be hard to figure out exactly what it means to code and how it plays role in your child' future coding (or computer programming)is the process of providing instructions to computer so it performs specific task you may have heard of popular text languages like javapythonor rubybut even kids can easily learn to code using visual block language like tynkerwhy is coding so importantbelieve it or notwe rely on code in the technology we use every day our mobile phonesthermostatstelevisionscarsand even the device you're using to read this wouldn' exist without code
7,838
in addition to the many practical and innovative uses for code in today' worldit is also creative medium with coding educationyour child can use their new skills to create almost anything they imaginemake apps games create animations mod minecraft control lego(rfly drones explore stem
7,839
when it comes to preparing your child for the futurethere are few better ways to do so than to help them learn to code coding can help your child develop academic skills applicable to any grade levelin addition to building critical life skills like organizationperseveranceand problem solving coding improves your child' academic performance it' been proven that learning to code reinforces math skillshelping kids visualize abstract concepts and apply math to real-world situations it also teaches logical communicationstrengthening both verbal and written skills learning to code means learning new languagecoding instills qualities like creativity that help kids perform better in school when they codekids learn through experimentation and strengthen their brainsallowing them to find creative solutions to problems
7,840
coding is basic literacy in the digital age it' important for your child to understand and be able to innovate with the technology around them as your child writes more complicated codethey'll naturally develop life skills like focus and organization it also develops resilience when kids codethey learn that it' ok to fail and improve there' no better way to build perseverance than working through challenges like debugging codekids also feel empowered to make difference when they code many kids in tynker' global community use the platform to spread messages of tolerance and kindness parents have even reported that their kids develop more confidence as they learn to problem-solve through coding
7,841
in today' rapidly evolving digital worldit' more important than ever that your child has the skills they need to adapt and succeed and coding is big part of that jobs are quickly becoming automatedand half of today' highest-paying jobs require some sort of coding knowledge by there will be million computer science-related jobs but only , computer science graduates to fill themaccording to the bureau of labor statistics at the very leastkids today must be familiar with basic coding concepts in order to prepare for the job market' demands and like learning second languagelearning code is best done at young age $ , median salary of software developer think basically every job in the future is going to have to require some part of coding!scoutstudent in australia
7,842
our award-winning creative computing platform helps kids develop computational thinking and programming skills in funintuitiveand imaginative way as they're guided through interactive game-based courseskids quickly learn fundamental programming concepts with tynkeryour child can apply their coding skills as they build gamestell storiesmod minecraftcreate appscontrol drones and robotsand morewe even offer parent dashboard where you can follow your child' success and share their creations interest-driven learning tynker' scaffolded curriculum is organized around interest-driven learning it' simple philosophy that means kids who already love to play with lego(ror barbie(rwill be more inclined (and genuinely excitedby the chance to integrate tynker with those interestsexpanding their potential to play as they learn kids begin to code using tynker' block-based visual languagewhich helps them recognize patterns and master programming concepts like sequencingloopsconditional logicand algorithmic thinking from therethey can flex their creativity by animating their own games and telling stories with code kids who' like to dive deeper into concepts from the classroom will enjoy creating projects with our stem tutorials and puzzles our interactive
7,843
their own pace for more hands-on learnersour drone and robot programming courses are the perfect way to apply coding to the world around them with the tynker appkids can program their own mini-drone to fly patternsperform flips and stuntsand even transport objects and with lego(rwedo kids can use programming to bring their lego(rcreations to lifegame-based learning experiences tynker' self-guided courses are made up of individual lessons designed to create fun and captivating learning experience lessons build upon each other to ensure concept masteryand guidance from interactive tutorials empowers kids to learn independently and at their own pace as they learnkids build mini-gamessolve puzzlescreate coding projectscomplete daily missionsearn exciting badgesand unlock new characters this is why kids love learning with tynker even though they're mastering important programming conceptsthey feel like they're just playing game
7,844
tynker introduces kids to coding with simple visual blocks this technique allows young makers to learn the fundamentals of programming and create incredible projects without the frustrations of syntax whenever they're readykids can start experimenting in those same block-based activities by switching between visual and text code blocks once kids become familiar with programming basics and syntaxthey can move to full text programming with swiftjavascriptand python
7,845
tynker' award-winning platform is used by over , schools and million kidsspanning more than countries global partners include brands like applemicrosoftmattelpbssylvan learningand more
7,846
tynker' game-based learning environment makes it easy for your child to learn to codeyour child will begin by using tynker' visual blocks to learn fundamental programming concepts through self-guided game-based activitiesthen graduate to text coding languages like javascriptpythonand swift as they gain confidence in their new abilities join tynker for free enroll in premium plan create free tynker account to give your child access to funfree coding activities access to our safeand secure tools is freeforever master skills five times faster with award-winning courses and tutorials watch kids learn to code and build amazing things get started with free coding puzzles code simple projects using tutorials create minecraft skins and mods safe secure , fun learning activities online courses ipad courses private minecraft server student progress tracking affordable flexible plans
7,847
tips for encouraging coding at home make screen time productive explore tynker' maker community get inspired by these kid coders how coding helps kids improve in other subjects improve writing abilities strengthen math performance develop creativit build focus and organization start earlygirls who "makechoose stem invest in your child' future add coding to your school' curriculum try an hour of code build makerspace for hands-on learning hear from tynker educatorwhy our cs programs are working
7,848
the best way to help your child learn to code is to treat it like any other extracurricular activity make habit out of itbuilding habit can take little timebut once your child integrates coding into their daily scheduleyou will see their learning accelerate and their engagement skyrocket check out the following articles for ways to make screen time more productivediscover some fun (and free!coding activities that you can do at home with your childand get inspired by other makers in tynker' global community
7,849
if you're concerned about the amount of screen time your kids are engaging inyou're not alone millions of parents worry that kids spend too much of their lives glued to screensand for good reason according to the bbcthe average child spends over hours each day looking at screen but we'll let you in on little secretyou can give in to your child' request for screen time by leveraging that time with upliftingengagingand creative activitiesit' trend on the riseand it' easier than you might think blend learning and fun leveraging screen time doesn' mean allowing your children to play only strictly educational games they don' need to be drilling math facts or learning history the key is to find ways to keep them thinking and creating let them discover that learning is fun
7,850
solving mysteries or puzzlesand codingencourage your kids to find inspiration in the world around them as they make art on their tablets when your kids look for game to playhelp them find game that uses problem-solving skills "he actually gets to use the skills that like to see him work onlike sharing artistic talentmusicartas well as math laurenfeatured maker noah' mother try having your kids program connected toys like drones or robots they're hugely popular for good reason kids get to use screens to createthen see the physical effects of their hard work and creativity in real-time it' entertainingof coursebut it also provides great feedback loopdistinguish between playing and making we all love little bit of mindless screen time now and then social media is to you as gaming is to kids but kids have an immense capability to learn and create that needs to be explored creativity is one of the most important skills your children can develop in facta recent forbes article cites creativity as the most important skill for future of aia good rule of thumb for leveraging your child' screen time is to find ways to focus on "makingrather than simply "playing when kids are playingthey're following predetermined paths when they're makingkids pave those paths here' an exampleyour child is playing gameclicking and draggingfollowing predetermined path she' enjoying herself and relaxingbut she' not as engaged as she could or should be when she switches to building her own gameshe' interacting with the platform in new way she' entertained by the prospect of challengeand pushes herself to learn new things in order to figure out how to create what she wants to make "my husband especially is very anti-screen timeso he doesn' like the kids just watching tv but this kind of activity is something [maxcan do where he' actually being productive there' difference between passively just absorbing something and then actively engaging with it stephaniefeatured maker max' mother
7,851
by creating opportunities for your kids to learn during their screen timeyou're helping them build good habits as they begin to discover the magic of makingkids might even take their making skills offline with artlegosor backyard fortsquell your screen time concerns by leveraging that time for learning kids thrive when they're challenged and they love to create what better way to encourage both"we don' do electronicswe don' do video gameswe don' do any of that stuff but could see the benefit from tynker thought "wowthis is really cool,so let them do it priscillafeatured maker isaiah' mother
7,852
what happens when more than million kids share coding projects with one another in supportive and collaborative spacea whole lot of fun and loads of teachingsharingand supportingwhen asked about their favorite tynker featurekids list things like the ease of coding with blocksthe ability to drawand almost unanimously the tynker communitywe are so excited by the way the tynker community has taken off we provide the framework and support for the communitybut all the trendsideasand teaching happening in the community is self-perpetuated it' constantly changing and improvingbut one thing stays constantit' always inspiring" like how when you look at the tynker community there are so many projects that are all so differentbut they're all made with the same software you look at the code and there' just so many opportunities for what you can make it' proof that everyone can come up with different thing from the same building blocksyou can make all the ideas that you have!featured maker scout
7,853
not only does the tynker community motivate and inspire kids to codebut it also helps them learnwhen we ask kids how they learned to use tynkerthey often cite the tynker community kids look at the code in community projects in order to learn how to code elements of their own games or projects in tynker we've even noticed kids making "how to use tynkertutorials as projects in tynker" ' trying to figure make joystick instead of the button system that have,mark said"but haven' figured out how to do that yet 've been looking at other projects to try to figure out how to do it featured maker mark they share ideas using tynker' toolskids have embraced the ability to truly create anything in their imaginationkids use tynker to share what' on their mindteach others skills (like how to draw turtle!make games to shareand even create educational math activities "it' not just codingbut it' also giving them an opportunity to learn other topicsand share what they know about other topicswhich thought was fantastic gurufeatured maker yaamini' father it' inspiring to see that when given freedom to make whatever they wantmany kids opt to educate about the environment or spread messages of respect few months agoone maker started trend around projects about respect and encouraging others to be more kind other kids caught on quicklythey support each other after kidssubmitted projects are approved and publishedthey garner likes and views from other users the praise kids get from their peers is exciting and validating
7,854
garnered within few days and over week she couldn' believe that her game was that popularand the view of her first game encouraged her to continue coding other games tynker parent love for coding (and common understanding of its difficultiesbonds the community togetherthey've all experienced the satisfaction of solving complicated problem and the frustrations along the way "almost everyone on tyner has made their own programso think that people kind of appreciate everyone else' hard work more tynker user supportive community is an asset to kids learning to code the ability to see what other young makers are up togive and receive positive feedbackand share their message is importantit' way for kids to teach and learn concepts like kindness as well as skills like animation (or how to make pancake!
7,855
hailing from all around the worldour featured makers begin their coding journeys in many different waysthey discover us through enthusiastic teacherssupportive parentsor all on their ownwe discover them as we approve each project for the tynker community each week we share the profile of child whose projects we're especially impressed by some create projects that are artistically stunning and others write complex code and all of the makers we feature inspire us with their hard work and dedication will your child be nextour featured makers all have big dreams and the determination to achieve them catch glimpse of some incredible kids who are coding up stormkindness advocatelayla th gradecalifornia kids spread kindness in the tynker communityone of the first to code projects about kindness and respect was ten-year-old layla she was inspired at school and chose tynker as the platform to spread her message she told us"my school had program about being leadersso wanted other people to be leaders and show respect to others started posting projects about respect and other people did it too not only does layla create projects advocating for better worldbut she codes projects full of tips for fellow tynkerersfuture cs phdaidan th gradesouth carolina tenacity and passion are great characteristics for young codersand it turns out eleven-year-old aidan is chock-full of bothduring our interviewhe showed us huge lego project he' working on and said"this one has pieces was building it all of yesterdayand only got two-thirds of the way done
7,856
csin his words" want to do something to do with computer science thanks to tynkeri have head start!creative storytellergrace rd gradescotland when grace grows upshe' like to become either doctor or coderin the meantimeshe' practicing by creating amazing stories on tynker " like to code because it' really fun to make your own game and decide what will happen in it,she says " like when other people like my projects it inspires me if someone has better game than me because it means can look at it and see what they've done and if can do anything different with my game we're so excited that grace has found support for her passions in the tynker communitystrong girl in stemscout th gradeaustralia every girl deserves to feel welcome and included in the stem worldand fourteen-year-old scout is helping to craft future in which women in stem is the norm scout is involved in club supporting coding for girls in her communityhas taught herself pythonand has deep understanding of the importance of learning coding according to her" definitely think that lots of people should try to get involved it' so importantat my schoolthere' not much codingso people should try to take advantage of all the opportunities that are given
7,857
every tynker user has their own reason to code and can relate coding to their dreams for their futureswhether those dreams include cs or not for anthonycomputer science gives him the tools to follow his passion gaminghe aspires to open massive gaming center his father used to ownand even wants to design games himself according to anthony" think every kid in the world should codeit' so funand it gets your brain thinking why not have no school and just code all daysame thingrightit gets your brain thinking!when you give your children and students bit of inspiration and access to tools that teachyou provide them with world of possibilities how will the kids in your life use tynker to express creativity and follow their dreamswe can' wait to see what they come up with
7,858
you've already read little bit about how your child benefits from learning to code you know that it can improve your child' academic performancedevelop important life skillsand prepare your child for the future read through this next section for deeper look at the ways coding helps your child as they learn and grow we cover how coding helps kids write betterearn better math gradesdevelop creativityand improve focus and organization you'll also learn why now is the time for your child to begin programminghow computer science prepares your child for the futureand why girls who create with code excel in stem fields there are so many reasons to help your child learn to code
7,859
developing strong writing skills especially when paired with technical abilities like coding all but guarantees your child success in school and beyond but did you know that writing and coding actually go hand in handwhen they learn to code and create digital storytelling projectschildren acquire skills that improve their writingand they have fun in the process coding is new medium for imaginative storytelling writer' tools for telling story include words and sentences coders have access to more open-ended mediumincluding picturesmusicand animation in addition to words the flexibility of programming even allows children to make their story react to audience input
7,860
it' be even better featured tynker maker grace writing script in story-based game forces kids to think through the exact details and consequences of how their characters act they can' be vague they have to hone their ideasan important skill that takes practice " rd graders created stories with dialogue and lively characters in tynker they were so caught up in creating and narrating their storiesthey didn' even realize they were codingwritingand crafting compelling storyline at the same time kathy bottarodigital learning program coordinatorsioux city community school districtiowa coding reduces the "blank pagesyndrome creating story-based game requires narrative pacingcompelling storylinesengaging dialogueand an understanding of the audience in shortit requires the same skills that some children struggle with when their english teacher hands out creative writing assignment the difference is that staring at blank sheet of paper often evokes panicbut programming offers multiple starting points when they codekids start with one characterthen experiment with dialoguemovementand interactions they build from there by adding other actorsscenesand interactions the program starts at the child' point of interest and evolves to final product through process of experimentation and iteration when codingthere is no "blank page,only discrete problems to be solved coding teaches the value of concision when kids first start codingit takes them five lines of code to program character to move across the screen as they learn more programming conceptslike loops and conditional statementsthey can condense that code to two lines children
7,861
disposal in the most powerful way possible to express ideas efficiently and directly these are the kids who will write -word college application essay that gets them noticed coding teaches planning and organizing skills programming and writing follow similar process when children start coding projectthey plan out the different functions they will need and how these functions will work together to make the project work likewiseto write an essaythey must organize their ideas into paragraphs and understand how the paragraphs fit together "coding helps develop the organizational skills required for good writing encourage my students to plan their writing assignments by breaking down their topicselecting the evidence they needand sequencing their points in compelling way some of the same skills are required when planning video game the more rigorous they are as they divide large problem into components and organize tasksthe more successful they will be lucinda rayeducator and writing instructor the interactive nature of programming makes challenging subjects more accessible whether your child loves to write or needs bit of helpcoding is fun activity that will supplement their language arts education
7,862
the conventional belief has always been that kids interested in coding should develop strong math skills howeverit turns out the reverse may also be truecoding can help children build math skills and make learning math more engaging and fun in the three years that casita centera magnet elementary school in southern californiahas been teaching coding with tynkerthey've seen considerable improvements in their studentsmath scoresoutperforming virtually all california schools with similar demographics jenny chienthe school' stem specialistbelieves this improvement is due to the effectiveness of their cs program when kids learn to codethey develop key skills like problem solving and practice algorithmic and computational thinking and when they learn to code with tynkerthey have fun at the same timeso they're more likely to stay engaged with the material these broad skill sets and ways of breaking down and analyzing problems translate across the curriculum and are particularly helpful when it comes to math whether kids are learning to code at school or at homeyou may just see an impact on their overall academic performancehere are few ways that coding helps kids learn math
7,863
grasping abstract math concepts can be challenge to many kids and put them off the subject entirely parentsteachersand technology specialists are using tynker to help children visualize abstract math concepts "one of the most common cross curricular benefits of computer programming is that the kids have an easier time learning math skills,says michelle lagosa computer science teacher who uses tynker in elementary classes at the american school in tegucigalpahonduras "when they have to work on long divisionit is easier for them to visualize the numbers now instead of counting with their fingers they visualize the equation and think of the best way to solve it lagos reports that she has "seen kids in many grades improve their math skillsby using tynker to learn coding jesse thorstadtechnology coordinator for the fergus falls public schools district in minnesotahas had similar experience "tynker provides kids with concrete example of the power of decimal places,he says "when studying decimals in maththe students experience heartwarming 'ah-ha!moment when they see how moving decimal block of code can affect the objects on the screen tenfold kids explore the real-world applications of math concepts repairing spaceships or saving puppies with tynker is great way for child to see concrete applications of math strategies tynker parent sri ramakrishnan points out that kids develop stronger math skills when applying concepts in real-world context"the computational thinking involved in computer programming involves logicorganizing and analyzing dataand breaking problem into smaller and more manageable parts much of this is also required when solving math problems!
7,864
kids who use tynker see how math is inherently creative -year-old jacob myersa big math buff who regularly competes in math contestsuses tynker to make math art with spirals and triangleskids can also complete activities like pattern maker and spin draw to learn how to create art with coding and math coding teaches problem-solving skills coding is real-world way to teach mathematical thinking when students create or debug programthey practice solving problems math teachers find that tynker' beginning lessons are great way to teach pattern identification as well teachers can assign activities like multiplication escape or analog clock and encourage students to find solutions with math coding makes math more fun "my kids ask to program with tynker because they enjoy it,says jennifer apythe parent of -year-oldan -year-oldand an -year-old "without realizing itmy kids are identifying attributes and grouping variablesapplying conditional logicdeveloping algorithmic functionsand calculating angles within geometric shapes but most of allthey are patiently articulating hypotheses to solve problemsand boldly applying trial-and-error experimentationstrategies required by any field of study and this is in addition to some of the coding that requires real math to correctly calculate wait timesset score counterscalculate pointsand time interactions between characters in their games "if kids realize they are using math when programming tynker games,apy says"it could actually build their confidence with math and show them that mathematical thinking can be cool math is coolwhat could be better than that
7,865
casey stares at his computer screencarefully calculating his next move as part of school science project to create simulation of the earth' tideshe has spent the better part of the hour trying to animate moon orbiting the eartha series of commands that is proving more complex than he had anticipated but with every iteration and tweakthe determined sixth grader finds himself inching closer to his vision finallyhe inputs - degrees on the coordinate on the yand hits enter he grins in giddy satisfaction as he watches his moon makes perfect circle around the earth casey' story is one of many that illustrates how the process of learning to code encourages one of the most important skills we can teach our kidscreativity we're all born with it as kidswe embrace imaginative playwe ask questionspaint colorful picturesand build elaborate things with our blocksbut somewhere along the way our capacity for creative thinking diminishes it' not because we lack the
7,866
developed at home and in our schools through the cultivation of three qualities an experimenter' mindset whole brain thinking an innate desire to be creator (and not just consumer programming teaches kids to experiment creative thinking begins with questioning mindset it can be taught by encouraging kids to experimentexplore their ideasquestion their assumptionsmake mistakes and learn from them thomas edison was master of this type of thinking he tested thousands of materials and processes before creating the first working light bulb " have successfully discovered , ways to not make light bulb,he famously said with programmingkids are exposed to this process of experimentation they start by learning handful of commands to do simple tasksand with each successful resultthey slowly gain the confidence try new and more ambitious thingsthings that force them to question each decision and ask "what if tried ?testing their assumptions in live environment frequently results in errors and bugsgiving kids the opportunity to find workable solution with practicekids gain proficiency in their technical and hypothesizing skillsallowing them to move onto solving increasingly complex problemsand eventually building programs completely on their own programming strengthens whole brain thinking each side of the brain is said to control different parts of thinking and information processing the left hemisphere is typically associated with logicaltechnicaland analytical thinkingwhereas the right hemisphere is associated with imaginationartisticintuitive thinking we tend to think of creativity as right-brain functionbut the most creative thinkers and problem solvers can effectively engage both hemispheres this idea of marrying "art with scienceis what steve jobs built apple onand it' this kind of "whole brainthinking that teachers have been embracing in the classroom by promoting activeproject based learningusing everything from
7,867
things learning programming with platform like tynker is particularly powerful because it requires kids to use their technical skills (to build the programin combination with their artistic and storytelling skills (to design program that is visually compelling and fun programming gives kids the confidence to create like learning sport or musical instrumentcultivating creativity requires hard work and practice for kidsif the work is confusingmonotonousor the end goal unappealingthe desire to practice weakens they need to be in an environment that builds confidence and instills in them genuine desire to create kids pick up on technology with shocking easeso giving them basic knowledge of programming on coding platform that is fun and easy to use is one of the best ways they can spend time in practice and actually enjoy the process learning programming on the right platformone that is structuredengaging and well pacedputs kids on the path to fluency in the language and logic of programmingand ultimately gives them springboard to create to not just play the games that they lovebut to create the games they love to play nurture creativity through programming learning to code is very much like learning new language it gives kids fluency not just in technologybut also in the language of creativity maria klawemathematiciancomputer scientist and president of harvey mudd believes that "coding is today' language of creativity all our children deserve chance to become creators instead of consumers of computer science it doesn' mean they'll all grow up to be computer programmers programming is part of the development of valuable technical and creative skill set that will grow with them into adulthoodenabling them to thrive in our ever growing digital world it' creativity that lays the foundation for innovationingenuity and leadership because it represents the ability to connect existing ideas with new solutionsapproaches and concepts and we owe it to our curious and imaginative kids to give them the tools to be the creative thinkers and problem solvers of the next generation
7,868
soft skills are popular notion in the business worldand they encompass qualities like leadershipcommunicationand perseverance although they may be difficult to measuresoft skills are vastly important for children to learn as founder and ceo krishna vedati told the bbc"our goal is not to create programmersbut to offer coding as life skill focus and organization are two soft skills that are the key towelleverythingin world where it' increasingly harder to focuseveryone could use boost especially kids coding is great example of an activity that requires focus and organizationbut more than thatit' fantastic way to develop those skills
7,869
it' no secret that the distractions we all face impact our ability to focusand kids are no exception to that between shows on tvgames on phonesand other distractionsthere' lot of opportunities for kids to lose focus the instant gratification found in these activities can make it difficult to focuswhich consequently makes it difficult to be organized "you speak to young kids nowadays and because of all this stimulus everywhere billboards and movies and everything going on the attentionthe focusjust isn' there alainfeatured maker elisha' father why organization and focus are key to coding organization goes hand in hand with focusespecially when it comes to writing complicated code in order to think through code logicallyit needs to be organized in an intuitive wayand vice versa the more complicated the codethe more programmer has to organizeincorporating elements like data structures to streamline the code "to meit' way of organizing ideasstructural thinkingand logical thinking it' challenging because kids are forced to think about how to solve problem santiagofeatured maker nico' father video game designer james hague reiterated this idea on his blogwriting"to great extent the act of coding is one of organization focus and organization are key to writing good codebut can coding help develop these skillsit' possiblehow learning to code develops focus and organization programming can help establish the focus and organization it relies onespecially when working with platform like tynker the goal-oriented nature of an exciting project promotes focus and organization in kids kids are motivated to finish
7,870
it happen" like to code because it is sometimes complex it' like when you're working up hill that has jewels at the top it' hard to get up itbut when you get to the top you're really proud and you think it' awesome featured maker anthony the logical nature of programming identifying problemthinking through stepsand then implementing solution encourages organization of thought and sustained focus paper written by roy pea and midian kurland argues that"in explicitly teaching the computer to do somethingit is contended that you learn more about your own thinking the focus and organization needed to problem solve from start to finish can be difficult to maintainbut it isn' impossible to develop as with any other activitycoding improves with practice as do the skills accompanying it inside and outside the classroomapplied to coding or homeworkthe focus and organization learned through programming will help kids in any endeavor
7,871
the growing shortage of women in computer science and engineering is hot topic these days fortunatelythe future looks bright for the next generation of girlsaccording to new study by intel their research finds that "girls that makedesign and create things using technology may develop stronger interest and greater skills in computer science and engineering the popularity of "diyand the maker movement are creating generation of girls and women who show just as much interest as boys in makinginventingand solving problems through technology according to intel in teens and tweens have already made things with technology and in are interested in learning to make things with electronics the key to getting more girls interested in stem is to expose them to making whether it be through designingbuildingcodingor the artsmaking provides them with pathway to learn and explore new ideas and technologies
7,872
tynker is popular coding platform for girls because of its fun and easy approachas well as the variety of projects and tools available to inspire their broad and creative interests girls have created millions of tynker projectssuch as greeting cardsmusic videoscomic cartoonsdigital storiesquiz gamesdrawing toolsmusic makersclassic arcade gamesplatformersgeometric designsminecraft mods and skinsand science fair projects let' hear from few who have enjoyed "makingwith tynker carly " like tynker because you can build whatever you want you can make video game or dancing video always try to build new things so can show my friends emma "it' really fun to see what you can do with tynker you can make game and if there' something you don' like about it you can change it and make it the way you like
7,873
imagination to make something awesome it' like drawing and painting and writing all mixed into one quinn "when do tynker it' just fun don' get stressed outbut know ' learning something haley "tynker is lot faster and simpler once built game in another language and it took me about days in tynker it takes about minutes to make good game
7,874
don' have to memorize lines of difficult code you just put the blocks together kami "tynker is easy and simple it' like sentenceyou just fill in the blocks you need to make it do what you want and it' easy to understand on mission to inspire more makers girls and women use technology more than ever it' time for more of them to create ittoo it' easy to become maker with code how do we get more kids (and girlsstartedby making it fun (and teaching them that there' rich history of women in stem careers)let' inspire more young makers to create with code and get more girls and boys to choose stem
7,875
in today' economywe are in urgent need of people with coding skills to meet the demands of burgeoning tech industry that isn' going to be shrinking anytime soon that' why introducing children to coding is crucial investment in their future coding is skill of the st centuryand with the rapid technological advancement of the modern ageit has quickly become as necessary skill as reading and arithmetic that is important for wide range of professions coding skills are in high demand the tech industry is in constant need of workers and it' not just coders or computer science majors they need graphic designerssoftware developerscomputer engineerslinguistsmathematicians the jobs are not only plentifulbut they're also lucrative
7,876
designmake an average of $ , year while linguists can come from wide range of concentrationsbeing computational linguist can earn you about $ , year and computer hardware engineers can easily make an average annual salary of $ , working in any of these fieldsand being able to code using javascriptpythonor any common computer programming languageis great step toward secure and stable job prepare your kids for high school and beyond like foreign languagecoding skills are best learned early once kids are fluent in the type of thinking required to break down and solve coding problemthe transition to any coding language is relatively straightforward tynker even transitions kids from block-based coding to javascript and python with fungamified courses the coding skills that tynker teaches lay the foundation that students need to succeed in high school and beyond one of the biggest obstacles to succeeding in high school or college-level computer science classes is lack of confidence in tackling the difficultunfamiliar material earlier exposure is the best solution being introduced to coding at an early age makes it easier to learn the hardermore technical aspects of computer science in high school and college in facta study by google and gallup shows that early exposure is one of the most important ways we can shrink the gender gap in stemas it boosts confidence in kidsespecially young girlswhile they're still interested in technology coding is lifelong skill even if your child wants to do something outside of computer science when they grow uptheir coding skills will prove useful across fields coding teaches problem solvingorganizationmathstorytellingdesigningand more the beauty of coding
7,877
themselves creatively to get your child interestedshow them what coding allows them to make coding allows them to do anything from writing stories and building video games to making minecraft mods and designing animations andof courseit' funtynker provides the easiest and most enjoyable path to learning how to code kids have so much fun that they hardly realize they're learning at all most importantlythe ability to code transforms kids from passive consumers into innovative creatorswith eyes that see every piece of technology as more than just toy but as problem to solve and an opportunity to create
7,878
coding at home is great startbut most of us want to see computer science taught to our children at schooltoounfortunatelythere' big disparity between what we would like as parents and the reality of the our education system today according to gallup pollwhile of parents want their child to study computer scienceonly of american schools teach computer programming the movement to bring coding to schools has can be led by parents like youin this sectionwe introduce some computer science programs that have been successful in schools these programs include hour of codea global movement to encourage students to learn programmingas well as makerspaces equipped with robotsdronesand more read up to see how you can empower your child' school to add coding to the curriculum
7,879
if your school is new to codingthere are plenty of free resources to get started even for teachers without computer science backgroundone quick way to get started is with tynker' hour of code tutorials hour of code is global movement that reaches millions of students in more than countries an initiative designed to get more kids engaged in computer sciencehour of code traditionally takes place during computer science education week in december but your child' school can run their own hour of code at any timeyou can help organize an hour of code for your child' school or your community with the help of our coding activities we created our hour of code tutorials with view to inspire and motivate beginning programmers children who know nothing about coding and are perhaps wary of it kids find it easy to drag and drop our visual code blocks to create simple gamesstoriesanimationsand more running an hour of code is great way to demystify the concept of programmingprovide early successesand share the positive impact of computer science education and when your child' class is ready to move beyond an hour of codebe sure to check out our full coding curriculum for schools
7,880
kids enjoy (and benefit from!hands-on learning schools can set up makerspace flexible learning space separate from the main teaching area where kids write programs to control dronesrobotsand more tynker integrates with variety of parrot minidronessphero robotsand the lego wedo to make it easy to equip makerspace for your child' classroom setting up makerspace gives tactile learners an opportunity to see their code play out in front of their eyes
7,881
working by stem coordinator jenny chien did you know that just one in ten schools nationwide currently are teaching computer science (csclassesprivate companiesthe federal governmentand states and districts have all invested to make these classes more available as cs classes and programs expandwe can learn some lessons from those that are already in place as stem specialist at dual magnet elementary schoolcasita centerin vista unified school districti' here to tell you what is working in the schools and districts where cs classes are already up and running big part of my job to work with other teachers and coordinators to design and implement curriculum to get elementary school students to learn computer science (csa robust part of the stem universe as backgroundthe vista unified school district has schools and serves about , students in san diego countycalifornia like many districtsvista united has title schoolshigh proportions of second language studentsand has made stem education priority the cs program we designed has done exactly what we hoped it would in pilot program at casita centerthe computer science implementation is factor that has boosted math test scores and enhanced other key skills including problem solving and critical thinking three years inwe were one of the top achieving schools in the state in mathematics compared to other schools with similar demographics and california is pretty bigpretty diverse state sowhat do we knowwhat are we doing rightand how did we get here
7,882
about the authors rahul verma rahul is software tester by choicewith focus on technical aspects of the craft he has explored the areas of security testinglarge scale performance engineering and database migration projects he has expertise in design of test automation frameworks rahul has presented at several conferencesorganizations and academic institutions his articles have been published in various magazines and forums he runs the website testing perspective www testingperspective com which he has got the testing thought leadership award he is member of the istqb advanced level technical test analyst and foundation level certification working parties you can reach him at rahul_verma@testingperspective com chetan giridhar chetan giridhar has years experience of working in software services industryserviceproduct companies and research organization he runs the website technobeans technobeans wordpress com where he shares his knowledge day-to-day usage of programming for testers chetan has strong background in ++javaperl and python he has developed tools and libraries for users and community developers that could be easily downloaded from chetan sourceforge he has written on wide variety of subjects in the field of securitycode reviews and agile methodologies for testing magazines including testingexperience and agilerecord he has given lectures on python programming at indian institute of astrophysics you can reach him at cjgiridhar@gmail com www testingperspective com
7,883
table of contents copyright information about the authors foreward preface why write this book what is design pattern context of design patterns in python design pattern classifications who this book is for what this book covers pre-requisites online version feedback model-view-controller pattern controller model view sample python implementation example description database python code explanation command pattern sample python implementation example description python code www testingperspective com
7,884
observer pattern sample python implementation example description python code facade pattern sample python implementation example description python code mediator pattern sample python implementation example description python code factory pattern sample python implementation example description python code proxy pattern sample python implementation example description python code refernces and further reading www testingperspective com
7,885
foreword vipul kocher shri ramkrishna paramhansone of the greatest mystics of this age and guru of swami vivekanandaused to narrate story that went like this "there was ghost who was very lonely it is said that when person dies an accidental death on tuesday or saturday becomes ghost whenever that ghost saw an accidental death he would rush there hoping he would find friend howeverevery time he was disappointed because all of them went to respective places without even one becoming ghost while he said it referring to difficulty of finding people with spiritual bent of mindi take the liberty of using this story for my own interests got drawn to object oriented design world in despite my job role being that of system tester started my career as developer and that probably was the reason or probably my love for abstract whatever be the reasoni got drawn to the world of grady booch,rumbaughshlaer and mellorcoad and yourdon etc then gang of four happened got blown away by the book design patterns elements of reusable object-oriented software since then kept looking for testers who shared same love as me for design patterns alasnone was to be found that isuntil met rahul verma and chetan giridhar used to wonder when automation framework developers would start talking about the framework as designer/architect rather than just as user will they ever take automation project as development projectwill they ever apply design patterns to the automation frameworkin the present book hope to see this dream of mine fulfilled while the book aims to talk of design patterns in pythoni hope to see the examples and explanations from the point of view of tester who wants to create framework utilizing sound architecture and design patterns patterns have begun to occupy large portion of my thought process for almost two years nowthe process having begun in with my first attempt at testing patterns by the name -patterns or questioning-patterns sincerely hope to see one piece of the pattern puzzle falling in place with this book hope you enjoy the journey that this book promises to take you through vipul kocher vipul kocher co-presidentpuretesting www testingperspective com
7,886
preface "testers are poor coders we here that more often than one would think there is prominent shade of truth in this statement as testers mostly code to --get the work done||at times using scripting languages which are vendor specificjust tweaking recorded script the quality of code written is rarely concern and most of the timesthe time and effort needed to do good coding is not allocated to test automation efforts the above scenario changes drastically when one needs to develop one' own testing frameworkextend an existing one or contribute new code to an existing one to retain the generic property of the framework and to build scalable frameworkstesters need to develop better coding skills why write this book wethe authors of this bookare testers we are in no way experts in the matter of design patterns or python we are learners we like object oriented programming we like python language we want to be better coders we have attempted to write this book in very simple languagepicking up simple examples to demonstrate given pattern and being as precise as possible this is done to provide text so that the concept of design patterns can reach to those who are not used to formal programming practices we hope that this would encourage other testers to pick up this subject in the interest better design of test automation what is design patternas per wikipediaa design pattern in architecture and computer science is formal way of documenting solution to design problem in particular field of expertise the idea was introduced by the architect christopher alexander in the field of architecture and has been adapted for various other disciplinesincluding computer science an organized collection of design patterns that relate to particular field is called pattern language in the object oriented worlddesign patterns tell us howin the context of certain problemwe should structure the classes and objects they do not translate directly into the solutionrather have to be adapted to suit the problem context with knowledge of design patternsyou can talk in --pattern language||because lot of known design patterns have been documented in discussionsone could ask www testingperspective com
7,887
--shouldn' we use for this implementation?|without talking about how classes would be implemented and how objects would be created it is similar to asking tester to do boundary value analysis (even bva should do!)rather than triggering long talk on the subject design patterns should not be confused with frameworks and libraries design patterns are not implementationsthough implementations might choose to use them context of design patterns in python python is ground-up object oriented language which enables one to do object oriented programming in very easy manner while designing solutions in pythonespecially the ones that are more than use-and-throw scripts which are popular in the scripting worldthey can be very handy python is rapid application development and prototyping language sodesign patterns can be very powerful tool in the hands of python programmer design pattern classifications creational patterns they describe how best an object can be created simple example of such design pattern is singleton class where only single instance of class can be created this design pattern can be used in situations when we cannot have more than one instances of logger logging application messages in file structural patterns they describe how objects and classes can work together to achieve larger results classic example of this would be the facade pattern where class acts as facade in front of complex classes and objects to present simple interface to the client behavioral patterns they talk about interaction between objects mediator design patternwhere an object of mediator classmediates the interaction of objects of different classes to get the desired process workingis classical example of behavioral pattern who this book is for if you are beginner to learning python or design patternsthis book can prove to be very easy-to-understand introductory text if you are testerin addition to the above this book would also be helpful in learning contexts in which design patterns can be used in the test automation world what this book covers www testingperspective com
7,888
this is an initial version of the book covering the following design patternsdp# model-view-controller pattern dp# command pattern dp# observer pattern dp# facade pattern dp# mediator pattern dp# factory pattern dp# proxy pattern because the current number of design patterns is handfulwe have not categorized them based on classifications mentioned earlier by the time we publish next version of this book with target of patternsthe content would be organized into classification-wise grouping of pre-requisites basic knowledge of object-oriented programming basic knowledge of python (see how would pareto learn python by rahul verma to get startedonline version an online version of the book is available on testing perspective website at the following linkthis version is more updated version of this ebook at any given point of time in terms of corrections and updated content we plan to release updated version of this offline pdf version at regular intervals to keep up with the updated content in online version feedback there would be mistakes some of them would be directly visible and some of them could be more subtle please write back to us so that we can correct the same you can use the contact form at testing perspective website to do so or write to us at feedback@testingperspective com www testingperspective com
7,889
dp the model-view-controller pattern introduction as per wikipedia"model-view-controller (mvcis software architecturecurrently considered an architectural pattern used in software engineering the pattern isolates "domain logic(the application logic for the userfrom input and presentation (gui)permitting independent developmenttesting and maintenance of each in mvc design patternthe application is divided into three interacting categories known as the modelthe view and the controller the pattern aims at separating out the inputs to the application (the controller part)the business processing logic (the model partand the output format logic (the view partin simple wordscontroller associates the user input to model and view model fetches the data to be presented from persistent storage www testingperspective com
7,890
view deals with how the fetched data is presented to the user let' talk about all these components in detailcontroller controller can be considered as middle man between user and processing (modelformatting (viewlogic it is an entry point for all the user requests or inputs to the application the controller accepts the user inputsparses them and decides which type of model and view should be invoked accordinglyit invokes the chosen model and then the chosen view to provide to the user what he/she/it requested model model represents the business processing logic of the application this component would be an encapsulated version of the application logic model is also responsible for working with the databases and performing operations like insertionupdate and deletion every model is meant to provide certain kind of data to the controllerwhen invoked furthera single model can return different variants of the same kind of data based on which method of the model gets called what exactly gets returned to the controllercould be controlled by passing arguments to given method of the model view viewalso referred as presentation layeris responsible for displaying the results obtained by the controller from the model component in way that user wants www testingperspective com
7,891
them to see or pre-determined format the format in which the data can be visible to users can be of any _typelike html or xml it is responsibility of the controller to choose view to display data to the user type of view could be chosen based on the model chosenuser configuration etc sample python implementation example description let' consider case of test management system that queries for list of defects here are two typical scenarios that work with any test management system if the user queries for particular defectthe test management system displays the summary of the defect to the user in prescribed format if the user searches for component it shows list of all defects logged against that component database let' consider sqlite db with the name _tmsand table defects tms [defectsid component summary xyz file doesn' get deleted xyz registry doesn' get created abc wrong title gets displayed download the sqlite database file heretms rar python code filenamemvc py import sqlite import types class defectmodeldef getdefectlist(selfcomponent)query '''select id from defects where component '% ''%component defectlist self _dbselect(querylist [for row in defectlistlist append(row[ ] www testingperspective com
7,892
return list def getsummary(selfid)query '''select summary from defects where id '% ''id summary self _dbselect(queryfor row in summaryreturn row[ def _dbselect(selfquery)connection sqlite connect('tms'cursorobj connection cursor(results cursorobj execute(queryconnection commit(cursorobj close(return results class defectviewdef summary(selfsummarydefectid)print "###defect summary for defect% ####\ % (defectid,summarydef defectlist(selflistcategory)print "###defect list for % ####\ncategory for defect in listprint defect class controllerdef __init__(self)pass def getdefectsummary(selfdefectid)model defectmodel(view defectview(summary_data model getsummary(defectidreturn view summary(summary_datadefectiddef getdefectlist(selfcomponent)model defectmodel(view defectview(defectlist_data model getdefectlist(componentreturn view defectlist(defectlist_datacomponentpython code for user import mvc controller mvc controller(displaying summary for defect id www testingperspective com
7,893
print controller getdefectsummary( displaying defect list for 'abccomponent print controller getdefectlist('abc'explanation controller would first get the query from the user it would know that the query is for viewing defects accordingly it would choose defectmodel if the query is for particular defectcontroller calls getsummary(method of defectmodelpassing the defect id as the argumentfor returning the summary of the defect then the controller calls summary(method of defectview and displays the response to the user if the user query consists of component namecontroller calls getdefectlist(method of defectmodelpassing the component name as the argumentfor returning the defect list for the given component then the controller calls defectlist(method of defectview and displays the response to the user www testingperspective com
7,894
dp command pattern introduction as per wikipedia"in object-oriented programmingthe command pattern is design pattern in which an object is used to represent and encapsulate all the information needed to call method at later time this information includes the method namethe object that owns the method and values for the method parameters command pattern is one of the design patterns that are categorized under _observerdesign pattern in command pattern the object is encapsulated in the form of commandi the object contains all the information that is useful to invoke method anytime user needs to give an examplelet say we have user interface where in the background of the interface would turn into red if the button on the user interface named _red|is clicked now the user is unaware what classes or methods the interface would call to make the background turn redbut the command user sends (by clicking on _redbuttonwould ensure the background is turned red thus command pattern gives the client (or the userto use the interface without the information of the actual actions being performedwithout affecting the client program the key to implementing this pattern is that the invoker object should be kept away from specifics of what exactly happens when its methods are executed this waythe same invoker object can be used to send commands to objects with similar interfaces www testingperspective com
7,895
command pattern is associated with three componentsthe clientthe invokerand the receiver let' take look at all the three components clientthe client represents the one that instantiates the encapsulated object invokerthe invoker is responsible for deciding when the method is to be invoked or called receiverthe receiver is that part of the code that contains the instructions to execute when corresponding command is given sample python implementation for demonstrating this patternwe are going to do python implementation of an example present on wikipedia in ++/java/cexample description it' the implementation of switch it could be used to switch on/off it should' be hard-coded to switch on/off particular thing ( lamp or an enginepython code class switch""the invoker class""def __init__(selfflipupcmdflipdowncmd)self __flipupcommand flipupcmd www testingperspective com
7,896
self __flipdowncommand flipdowncmd def flipup(self)self __flipupcommand execute(def flipdown(self)self __flipdowncommand execute(class light"""the receiver class""def turnon(self)print "the light is ondef turnoff(self)print "the light is offclass command"""the command abstract class""def __init__(self)pass #make changes def execute(self)#override pass class flipupcommand(command)"""the command class for turning on the light""def __init__(self,light)self __light light def execute(self)self __light turnon(class flipdowncommand(command)"""the command class for turning off the light""def __init__(self,light)command __init__(selfself __light light def execute(self)self __light turnoff(class lightswitch""the client class"" www testingperspective com
7,897
def __init__(self)self __lamp light(self __switchup flipupcommand(self __lampself __switchdown flipdowncommand(self __lampself __switch switch(self __switchup,self __switchdowndef switch(self,cmd)cmd cmd strip(upper(tryif cmd ="on"self __switch flipup(elif cmd ="off"self __switch flipdown(elseprint "argument \"on\or \"off\is required except exceptionmsgprint "exception occured%smsg execute if this file is run as script and not imported as module if __name__ ="__main__"lightswitch lightswitch(print "switch on test lightswitch switch("on"print "switch off testlightswitch switch("off"print "invalid command testlightswitch switch("****" www testingperspective com
7,898
dp observer pattern introduction as per wikipedia"the observer pattern ( subset of the publish/subscribe patternis software design pattern in which an objectcalled the subjectmaintains list of its dependantscalled observersand notifies them automatically of any state changesusually by calling one of their methods it is mainly used to implement distributed event handling systems typically in the observer patternwe would have publisher class that would contain methods forregistering other objects which would like to receive notifications notifying any changes that occur in the main object to the registered objects (via registered object' methodunregistering objects that do not want to receive any further notifications subscriber class that would containa method that is used by the publisher classto notify the objects registered with itof any change that occurs an event that triggers state change that leads the publisher to call its notification method www testingperspective com
7,899
to summarizesubscriber objects can register and unregister with the publisher object so whenever an eventthat drives the publisher' notification methodoccursthe publisher notifies the subscriber objects the notifications would only be passed to the objects that are registered with the subject at the time of occurrence of the event sample python implementation example description let' take the example of techforum on which technical posts are published by different users the users might subscribe to receive notifications when any of the other users publishes new post to see this in the light of objectswe could have _techforumobject and we can have another list of objects called _userobjects that are registered to the _techforumobjectthat can observe for any new posts on the _techforumalong with the new post notificationthe title of the post is sent similar analogy could be drawn in terms of job agency and job seekers/employers this could be an extension where employers and job seekers subscribe to two different kinds of notification via common subject (job agencyjob seekers would be looking for relevant job notifications and employers would be looking for new job seeker registration fitting job profile python code class publisherdef __init__(self)#make it uninheritable pass def register(self)#override pass def unregister(self)#override pass def notifyall(self)#override pass class techforum(publisher)def __init__(self)self _listofusers [self postname none www testingperspective com