id
int64
0
25.6k
text
stringlengths
0
4.59k
8,000
builder pattern development process in the real world with some languageslike javayou can overload the constructor with many different options in terms of the parameters accepted and what is then constructed in turn alsonotice that the if conditional in the constructor __init__(could be defined more clearly ' sure you have lot of objections to this implementationand you should before we clean it up little morewe are going to quickly look at anti-patterns anti-patterns an anti-pattern isas the name suggeststhe opposite of software pattern it is also something that appears regularly in the process of software development anti-patterns are usually general way to work around or attempt to solve specific type of problembut are also the wrong way to solve the problem this does not mean that design patterns are always the right way what it means is that our goal is to write clean code that is easy to debugeasy to updateand easy to extend anti-patterns lead to code that is exactly the opposite of these stated goals they produce bad code the problem with the telescoping constructor anti-pattern is that it results in several constructorseach with specific number of parametersall of which then delegate to default constructor (if the class is properly writtenthe builder pattern does not use numerous constructorsit uses builder object instead this builder object receives each initialization parameter step by step and then returns the resulting constructed object as single result in the webform examplewe want to add the different fields and get the generated webform as result an added benefit of the builder pattern is that it separates the construction of an object from the way the object is representedso we could change the representation of the object without changing the process by which it is constructed in the builder patternthe two main players are the builder and the director the builder is an abstract class that knows how to build all the components of the final object in our casethe builder class will know how to build each of the field types it can assemble the various parts into complete form object the director controls the process of building there is an instance (or instancesof builder that the director uses to build the webform the output from the director is fully initialized object--the webformin our example the director implements the set of instructions for setting up webform from the fields it contains this set of instructions is independent of the types of the individual fields passed to the director
8,001
builder pattern generic implementation of the builder pattern in python looks like thisform_builder py from abc import abcmetaabstractmethod class director(objectmetaclass=abcmeta)def __init__(self)self _builder none @abstractmethod def construct(self)pass def get_constructed_object(self)return self _builder constructed_object class builder(objectmetaclass=abcmeta)def __init__(selfconstructed_object)self constructed_object constructed_object class product(object)def __init__(self)pass def __repr__(self)pass class concretebuilder(builder)pass class concretedirector(director)pass you see we have an abstract classbuilderwhich forms the interface for creating objects (productthenthe concretebuilder provides an implementation for builder the resulting object is able to construct other objects
8,002
builder pattern using the builder patternwe can now redo our webform generator from abc import abcmetaabstractmethod class director(objectmetaclass=abcmeta)def __init__(self)self _builder none def set_builder(selfbuilder)self _builder builder @abstractmethod def construct(selffield_list)pass def get_constructed_object(self)return self _builder constructed_object class abstractformbuilder(objectmetaclass=abcmeta)def __init__(self)self constructed_object none @abstractmethod def add_text_field(selffield_dict)pass @abstractmethod def add_checkbox(selfcheckbox_dict)pass @abstractmethod def add_button(selfbutton_dict)pass class htmlform(object)def __init__(self)self field_list [
8,003
builder pattern def __repr__(self)return "{}format("join(self field_list)class htmlformbuilder(abstractformbuilder)def __init__(self)self constructed_object htmlform(def add_text_field(selffield_dict)self constructed_object field_list append'{ }:formatfield_dict['label']field_dict['field_name'def add_checkbox(selfcheckbox_dict)self constructed_object field_list append{ }formatcheckbox_dict['field_id']checkbox_dict['value']checkbox_dict['label'def add_button(selfbutton_dict)self constructed_object field_list append'{}formatbutton_dict['text'class formdirector(director)def __init__(self)director __init__(self
8,004
builder pattern def construct(selffield_list)for field in field_listif field["field_type"="text_field"self _builder add_text_field(fieldelif field["field_type"="checkbox"self _builder add_checkbox(fieldelif field["field_type"="button"self _builder add_button(fieldif __name__ ="__main__"director formdirector(html_form_builder htmlformbuilder(director set_builder(html_form_builderfield_list "field_type""text_field""label""best text you have ever written""field_name""field one}"field_type""checkbox""field_id""check_it""value"" ""label""check for on"}"field_type""text_field""label""another text field""field_name""field one}"field_type""button""text""done
8,005
builder pattern director construct(field_listwith open("form_file html"' 'as ff write"{ ! }formatdirector get_constructed_object(our new script can only build forms with text fieldscheckboxesand basic button you can add more field types as an exercise one of the concretebuilder classes has the logic needed for the creation of the webform you want director calls the create(method in this waythe logic for creating different kinds of products gets abstracted note how the builder pattern focuses on building the form step by step this is in stark contrast to the abstract factorywhere family of products can be created and returned immediately using polymorphism since the builder pattern separates the construction of complex object from its representationyou can now use the same construction process to create forms in different representationsfrom native app interface code to simple text field an added benefit of this separation is reduction in object sizewhich leads to cleaner code we have better control over the construction process and the modular nature allow us to easily make changes to the internal representation of objects the biggest downside is that this pattern requires that we create concretebuilder builders for each type of product that you want to create sowhen should you not use the builder patternwhen you are constructing mutable objects that provide means of modifying the configuration values after the object has been constructed you should also avoid this pattern if there are very few constructorsthe constructors are simpleor there are no reasonable default values for any of the constructor parameters and all of them must be specified explicitly  note on abstraction when we talk about abstractionin the most basic terms we refer to the process of associating names to things machine code is abstracted in using labels for the machine instructionswhich are set of hexadecimal instructionswhich in turn is an
8,006
builder pattern abstraction of the actual binary numbers in the machine with pythonwe have further level of abstraction in terms of objects and functions (even though also has functions and librariesexercises implement radio group generation function as part of your form builder extend the form builder to handle post-submit data and save the incoming information in dictionary implement version of the form builder that uses database table schema to build form interface to the database table code up an admin interface generator that auto-generates forms to deal with information to and from database you can pass schema in as string to the form builder and then have it return the html for the formplus some submit url extend the form builder so you have two new objectsone to create an xml version of the form and another to generate json object containing the form information
8,007
adapter pattern it is not the strongest of the species that survivesnor the most intelligent it is the one that is most adaptable to change --charles darwin sometimes you do not have the interface you would like to connect to there could be many reasons for thisbut in this we will concern ourselves with what we can do to change what we are given into something that is closer to what we would like to have let' say you want to build your own marketing software you begin by writing some code to send emails in the larger systemyou might make call like thissend_email py import smtplib from email mime text import mimetext def send_email(senderrecipientssubjectmessage)msg mimetext(messagemsg['subject'subject msg['from'sender msg['to'",join(recipientsmail_sender smtplib smtp('localhost'mail_sender send_message(msgmail_sender quit(if __name__ ="__main__"response send_email'me@example com'["peter@example com""paul@example com""john@example com"]"this is your message""have good day(cwessel badenhorst badenhorstpractical python design patterns
8,008
adapter pattern nextyou implement an email sender as classsince by now you suspect that if you are going to build larger systems you will need to work in an object-oriented way the emailsender class handles the details of sending message to user users are stored in comma-separated values (csvfilewhich you load as needed users csv namesurnameemail peterpotterpeter@example comma here is what your email-sending class might look like on first passmail_sender py import csv import smtplib from email mime text import mimetext class mailer(object)def send(senderrecipientssubjectmessage)msg mimetext(messagemsg['subject'subject msg['from'sender msg['to'[recipientss smtplib smtp('localhost' send_message(recipients quit(if __name__ ="__main__"with open('users csv'' 'as csv_filereader csv dictreader(csv_fileusers [ for row in readermailer mailer(mailer send'me@example com'[ ["email"for in users]"this is your message""have good day
8,009
adapter pattern for this to workyou might need some sort of email service set up on your operating system postfix is good free option should you need it before we continue with the examplei would like to introduce two design principles that you will see many times in this book these principles provide clear guide to writing better code don' repeat yourself (drydesign principles like dry are guiding lights in the forest of problems and challenges you need to overcome in any software project they are little voices in the back of your headguiding you toward cleanclearand maintainable solution you will be tempted to skip over thembut doing so should leave you feeling uncomfortable when you have dark corners in your code where no one likes to goit is probably because the original developer did not follow these guidelines will not lie to youin the beginningit is hard it often takes little longer to do things the right waybut in the long runit is worth it in the gang of four book (the original tome on object-oriented design patterns)the two main principles proposed by the authors for solving common problems are as followsprogram to an interfacenot an implementation favor object composition over inheritance keeping the first principle in mindwe would like to change the way we get user data so that we no longer deal with the implementation of data fetching inside the emailsender class we want to move this part of the code out into separate class in such way that we are no longer concerned with how the data is retrieved this will allow us to swap out the file system for database of some sortor even remote microserviceshould that be required in the future separation of concern programming to an interface allows us to create better separation between the code that gets user details and the code that sends the message the more clearly you separate your system into distinct unitseach with its own concern or taskand the more independent of one another these sections arethe easier it becomes to maintain and extend the system as long as you keep the interface fixedyou are able to switch to newer and better ways of doing things without requiring complete overall of your
8,010
adapter pattern existing system in the real worldthis can mean the difference between system that is stuck with cobol base and magnetic tape and one that moves with the times it also has the added bonus of allowing you to course correct more easily should you find that one or more design decisions you made early on were sub-optimal this design principle is called separation of concern (soc)and sooner or later you will either be very thankful you adhered to it or very sorry that you did not you have been warned let' follow our own advice and separate the retrieval of user information from the emailsender class user_ fetcher py class userfetcher(object)def __init__(source)self source source def fetch_users()with open(self source' 'as csv_filereader csv dictreader(csv_fileusers [ for row in readerreturn rows mail_sender py import csv import smtplib from email mime text import mimetext class mailer(object)def send(senderrecipientssubjectmessage)msg mimetext(messagemsg['subject'subject msg['from'sender msg['to'[recipientss smtplib smtp('localhost' send_message(recipients quit(
8,011
adapter pattern if __name__ ="__main__"user_fetcher userfetcher('users csv'mailer mailer(mailer send'me@example com'[ ["email"for in user_fetcher fetch_users()]"this is your message""have good daycan you see how it might take bit of effort to get this rightbut how much easier it will be when we want to drop in postgresredisor some external api without changing the code that does the actual sending of the emailnow that you have this beautiful piece of code that sends emails to usersyou might get request for your code to be able to send status updates to social media platform like facebook or twitter you do not want to change your working email-sending codeand you found package or program online that can handle the other side of the integration for you how could you create some sort of messaging interface that would allow you to send messages to many different platforms without changing the code doing the sending to fit each targetor reinventing the wheel to fit your needsthe more general problem we want to solve isthe interface have is not the interface wantas with most common software problemsthere is design pattern for that let' work on sample problem first so we can develop bit of intuition about the solution before we implement it for the problem we have at hand let' begin by oversimplifying the problem we want to plug one piece of code into anotherbut the plug does not fit the socket when trying to charge your laptop when traveling to another countryyou need to get some sort of adapter to adapt your charger plug to the wall socket in our everyday liveswe have adapters for switching between two-pronged plugs and three-pronged socketsor for using vga screens with hdmi outputs or other physical devices these are all physical solutions for the problem of the interface have is not the interface wantwhen you are building everything from the ground upyou will not face this problembecause you get to decide the level of abstraction you are going to use in your system and how the different parts of the system will interact with one another in the real worldyou rarely get to build everything from scratch you have to use the plugin
8,012
adapter pattern packages and tools available to you you need to extend code you wrote year ago in way that you never consideredwithout the luxury to go back and redo everything you did before every few weeks or monthsyou will realize that you are no longer the programmer you were before--you became better--but you still need to support the projects (and mistakesyou previously made you will need interfaces you do not have you will need adapters sample problem we said that we want an adapterwhenever really we want specific interface that we do not have class whatihave(object)def provided_function_ (self)pass def provided_function_ (self)pass class whatiwant(object)def required_function()pass the first solution that comes to mind is simply changing what we want to fit what we have when you only need to interface with single objectyou are able to do thisbut let' imagine we want to also use second serviceand now we have second interface we could begin by using an if statement to direct the execution to the right interfaceclass client(objectdef __init__(some_object)self some_object some_object def do_something()if self some_object __class__ =whatihaveself some_object provided_function_ (self some_object provided_function_ (else if self some_object __class__ =whatiwantself some_object required_function(elseprint("class of self some_object not recognized"
8,013
adapter pattern in system where we have only two interfacesthis is not bad solutionbut by now you know that very rarely will it stay just the two systems what also tends to happen is that different parts of your program might make use of the same service suddenlyyou have multiple files that need to be altered to fit every new interface you introduce in the previous you realized that adding to system by creating multipleoften telescopingif statements all over the place is rarely the way to go you want to create piece of code that goes between the library or interface you have and makes it look like the interface you want adding another similar service will then simply entail adding another interface to that serviceand thus your calling object becomes decoupled from the provided service class adapter one way of attacking this problem is to create several interfaces that use polymorphism to inherit both the expected and the provided interfaces sothe target interface can be created as pure interface class in the example that followswe import third-party library that contains class called whatihave this class contains two methodsprovided_function_ and provided_function_ which we use to build the function required by the client object from third_party import whatihave class whatiwantdef required_function(self)pass class myadapter(whatihavewhatiwant)def __init__(selfwhat_i_have)self what_i_have what_i_have def provided_function_ (self)self what_i_have provided_function_ def provided_function_ (self)self what_i_have profided_function_ def required_function(self)self provided_function_ (self provided_function_ (
8,014
adapter pattern class clientobject()def __init__(selfwhat_i_want)self what_i_want what_i_want def do_something()self what_i_want required_function(if __name__ ="__main__"adaptee whatihave(adapter myadapter(adapteeclient clientobject(adapterclient do_something(adapters occur at all levels of complexity in pythonthe concept of adapters extends beyond classes and their instances oftencallables are adapted via decoratorsclosuresand functools there is yet another way that you could adapt one interface to anotherand this one is even more pythonic at its core object adapter pattern instead of using inheritance to wrap classwe could make use of composition an adapter could then contain the class it wraps and make calls to the instance of the wrapped object this approach further reduces the implementation complexity class objectadapter(interfacesuperclass)def __init__(selfwhat_i_have)self what_i_have what_i_have def required_function(self)return self what_i_have provided_function_ (def __getattr__(selfattr)everything else is handled by the wrapped object return getattr(self what_i_haveattrour adapter now only inherits from interfacesuperclass and takes an instance as parameter in its constructor the instance is then stored in self what_i_have
8,015
adapter pattern it implements required_function methodwhich returns the result of calling the provided_function_ (method of its wrapped whatihave object all other calls on the class are passed to its what_i_have instance via the ___getattr__(method you still only need to implement the interface you are adapting objectadapter does not need to inherit the rest of the whatihave interfaceinsteadit supplies __getattr__(to provide the same interface as the whatihave classapart from the methods it implements itself the __getattr__(methodmuch like the __init__(methodis special method in python often called magic methodsthis class of methods is denoted by leading and trailing double underscoressometimes referred to as double under or dunder when the python interpreter does an attribute lookup on the object but can' find itthe __getattr__(method is calledand the attribute lookup is passed to the self what_i_ have object since python uses concept called duck typingwe can simplify our implementation some more duck typing duck typing says that if an animal walks like duck and quacks like duckit is duck put in terms we can understandin python we only care about whether an object offers the interface elements we need if it doeswe can use it like an instance of the interface without the need to declare common parent interfacesuperclass just lost its usefulness and can be removed nowconsider the objectadapter as it makes full use of duck typing to get rid of the interfacesuperclass inheritance from third_party import whatihave class objectadapter(object)def __init__(selfwhat_i_have)self what_i_have what_i_have def required_function(self)return self what_i_have provided_function_ (def __getattr__(selfattr)everything else is handeled by the wrapped object return getattr(self what_i_haveattr
8,016
adapter pattern the code does not look any differentother than having the default object instead of interfacesuperclass as parent class of the objectadapter class this means that we never have to define some super class to adapt one interface to another we followed the intent and spirit of the adapter pattern without all the run-around caused by lessdynamic languages rememberyou are not slave to the way things were defined in the classic texts of our field as technology grows and changesso too must wethe implementers of that technology our new version of the adapter pattern uses composition rather than inheritance to deliver more pythonic version of this structural design pattern thuswe do not require access to the source code of the interface class we are given thisin turnallows us to not violate the open/closed principle proposed by bertrand meyercreator of the eiffel programming languageand the idea of design by contract the open/closed principle statessoftware entities (classesmodulesfunctionsetc should be open for extensionbut closed for modification you want to extend the behavior of an entity without ever modifying its source code when you want to learn something newespecially when it is not trivial bit of informationyou need to understand the information on deep level an effective strategy for gaining deeper understanding is to deconstruct the big picture into smaller parts and then simplify those into digestible chunks you then use these simple chunks to develop an intuitive sense of the problem and its solution once you gain confidence in your abilityyou let in more of the complexity once you have deep understanding of the partsyou continue to string them back togetherand you will find that you have much clearer sense of the whole you can use the process we just followed whenever you want to begin exploring new idea implementing the adapter pattern in the real world since you now have feel for clearpythonicimplementation of the adapter patternlet' apply that intuition to the case we looked at in the beginning of this we are going to create an adapter that will allow us to write text to the command line in order to show you what the adapter pattern looks like in action as part of the exercisesyou will be challenged to create an adapter to one of the social network libraries for python and integrate that with the code that follows
8,017
adapter pattern import csv import smtplib from email mime text import mimetext class mailer(object)def send(senderrecipientssubjectmessage)msg mimetext(messagemsg['subject'subject msg['from'sender msg['to'[recipientss smtplib smtp('localhost' send_message(recipients quit(class logger(object)def output(message)print("[logger]format(message)class loggeradapter(object)def __init__(selfwhat_i_have)self what_i_have what_i_have def send(senderrecipientssubjectmessage)log_message "from{}\nto{}\nsubject{}\nmessage{}formatsenderrecipientssubjectmessage self what_i_have output(log_messagedef __getattr__(selfattr)return getattr(self what_i_haveattrif __name__ ="__main__"user_fetcher userfetcher('users csv'mailer mailer(mailer send'me@example com'
8,018
adapter pattern [ ["email"for in user_fetcher fetch_users()]"this is your message""have good dayyou may just as well use the logger class you developed in in the preceding examplethe logger class is just used as an example for every new interface you want to adaptyou need to write new adapterobject type class each of these is constructed with two arguments in its constructorone of which is an instance of the adaptee each of the adapters also needs to implement the send_message(selftopicmessage_bodymethod with the required parameters so it can be called using the desired interface from anywhere in the code if the parameters we pass to each provided_function remain the same as those of the required_functionwe could create more generic adapter that no longer needs to know anything about the adapteewe simply supply it an object and the provided_ functionand we're done this is what the generic implementation of the idea would look likeclass objectadapter(object)def __init__(selfwhat_i_haveprovided_function)self what_i_have what_i_have self required_function provided_function def __getattr__(selfattr)return getattr(self what_i_haveattrimplementing the message-sending adapter in this way is also one of the exercises at the end of this by now you may have realized that you have to do more and more of the implementation yourself this is by design the aim is to guide you in the learning process you should be implementing the code so you gain more intuition about the concepts they address once you have working versionfiddle with itbreak itthen improve upon it arting shots you saw that adapters are useful when you need to make things work after they are designed it is way of providing different interface to subjects to which the interface are provided from the interface provided
8,019
adapter pattern the adapter pattern has the following elementstarget defines the domain-specific interface the client uses client uses objects that conform to the target interface adaptee the interface you have to alter because the object does not conform to the target adapter the code that changes what we have in the adaptee to what we want in the client to implement the adapter patternfollow this simple process define what the components are that you want to accommodate identify the interfaces the client requires design and implement the adapters to map the client' required interface to the adaptee' provided interface the client is decoupled from the adaptee and coupled to the interface this gives you extensibility and maintainability exercises extend the user-fetcher class to be able to fetch from csv file or sqlite database pick any modern social network that provides an api to interact with the network and post messages of some sort nowinstall the python library for that social network and create class and an object adapter for said library so the code you have developed in this can be used to send message to that social network once doneyou can congratulate yourself on building the basis of many large businesses that offer scheduled social media messages rewrite your code from the previous exercise to make use of the generic adapter for all of the interfaces you implemented
8,020
decorator pattern time abides long enough for those who make use of it --leonardo da vinci as you become more experiencedyou will find yourself moving beyond the type of problems that can easily be solved with the most general programming constructs at such timeyou will realize you need different tool set this focuses on one such tool when you are trying to squeeze every last drop of performance out of your machineyou need to know exactly how long specific piece of code takes to execute you must save the system time before you initiate the code to be profiledthen execute the codeonce it has concludedyou must save the second system timestamp finallysubtract the first time from the second to obtain the time elapsed during the execution look at this example for calculating fibonacci numbers fib py import time start_time time time(fibprev fib for num in range( )fibprevfib fibfib fibprev end_time time time(print("[time elapsed for {}{}format(nend_time start_time)print("fibonacci number for {}{}format(nfibiter( ))(cwessel badenhorst badenhorstpractical python design patterns
8,021
decorator pattern every system is differentbut you should get result shaped like the one here[time elapsed for - fibonacci number for we now extend our fibonacci code so we can request the number of elements in the fibonacci sequence we wish to retrieve we do this by encapsulating the fibonacci calculation in function fib_ function py import time def fib( )start_time time time(if return fibprev fib for num in range( )fibprevfib fibfib fibprev end_time time time(print("[time elapsed for {}{}format(nend_time start_time)return fib if __name__ ="__main__" print("fibonacci number for {}{}format(nfib( ))in the preceding codethe profiling takes place outside of the function itself this is fine when you only want to look at single functionbut this is not usually the case when you are optimizing program luckilyfunctions are first-class citizens in pythonand as such we can pass the function as parameter to another function solet' create function to time the execution of another function
8,022
decorator pattern fib_ func_profile_me py import time def fib( )if return fibprev fib for num in range( )fibprevfib fibfib fibprev return fib def profile_me(fn)start_time time time(result (nend_time time time(print("[time elapsed for {}{}format(nend_time start_time)return result if __name__ ="__main__" print("fibonacci number for {}{}format(nprofile_me(fibn))whenever we want to get the time it takes to execute functionwe can simply pass the function into the profiling function and then run it as usual this approach does have some limitationssince you must pre-define the parameters you want applied to the timed function yet againpython comes to the rescue by allowing us to also return functions as result instead of calling the functionwe now return the function with the profiling added on base_profiled_ fib py import time def fib( )if return
8,023
decorator pattern fibprev fib for num in range( )fibprevfib fibfib fibprev return fib def profile_me(fn)start_time time time(result (nend_time time time(print("[time elapsed for {}{}format(nend_time start_time)return result def get_profiled_function( )return lambda nprofile_me(fnif __name__ ="__main__" fib_profiled get_profiled_function(fibprint("fibonacci number for {}{}format(nfib_profiled( ))this method works lot better but still requires some effort when trying to profile several functionsas this causes interference with the code executing the function there has to be better way ideallywe want way to tag specific function as one to be profiledand then not worry about the call that initiates the function call we will do this using the decorator pattern the decorator pattern to decorate functionwe need to return an object that can be used as function the classic implementation of the decorator pattern uses the fact that the way python implements regular procedural functions these functions can be seen as classes with some kind of execution method in pythoneverything is an objectfunctions are objects with special __call__(method if our decorator returns an object with __call__(methodthe result can be used as function
8,024
decorator pattern the classic implementation of the decorator pattern does not use decorators in the sense that they are available in python once againwe will opt for the more pythonic implementation of the decorator patternand as such we will leverage the power of the built-in syntax for decorators in pythonusing the symbol class_decorated_profiled_ fib py import time class profilingdecorator(object)def __init__(selff)print("profiling decorator initiated"self def __call__(self*args)start_time time time(result self (*argsend_time time time(print("[time elapsed for {}{}format(nend_time start_time)return result @profilingdecorator def fib( )print("inside fib"if return fibprev fib for num in range( )fibprevfib fibfib fibprev return fib if __name__ ="__main__" print("fibonacci number for {}{}format(nfib( ))
8,025
decorator pattern the print statement inside the fib function is just there to show where the execution fits relative to the profiling decorator remove it once you see it in action so as to not influence the actual time taken for the calculation profiling decorator initiated inside fib [time elapsed for - fibonacci number for in the class definitionwe see that the decorated function is saved as an attribute of the object during initialization thenin the call functionthe actual running of the function being decorated is wrapped in time requests just before returningthe profile value is printed to the console when the compiler comes across the @profilingdecorator_it initiates an object and passes in the function being wrapped as an argument to the constructor the returned object has the __call__(function as methodand as such duck typing will allow this object to be used as function alsonote how we used *args in the __call__(method' parameters to pass in arguments *args allows us to handle multiple arguments coming in this is called packingas all the parameters coming in are packed into the args variable thenwhen we call the stored function in the attribute of the decorating objectwe once again use *args this is called unpackingand it turns all the elements of the collection in args into individual arguments that are passed on to the function in question the decorator is unary function ( function that takes single argumentthat takes function to be decorated as its argument as you saw earlierit then returns function that is the same as the original function with some added functionality this means that all the code that interacts with the decorated function can remain the same as when the function was undecorated this allows us to stack decorators soin silly examplewe could profile our fibonacci function and then output the result string as html stacked_ fib py import time class profilingdecorator(object)def __init__(selff)print("profiling decorator initiated"self
8,026
decorator pattern def __call__(self*args)print("profilingdecorator called"start_time time time(result self (*argsend_time time time(print("[time elapsed for {}{}format(nend_time start_time)return result class tohtmldecorator(object)def __init__(selff)print("html wrapper initiated"self def __call__(self*args)print("tohtmldecorator called"return "{}format(self (*args)@tohtmldecorator @profilingdecorator def fib( )print("inside fib"if return fibprev fib for num in range( )fibprevfib fibfib fibprev return fib if __name__ ="__main__" print("fibonacci number for {}{}format(nfib( ))
8,027
decorator pattern this results in the following output when decorating functionbe careful to take note what the output type of the function you wrap is and also what the output type of the result of the decorator is more often than notyou want to keep the type consistent so functions using the undecorated function do not need to be changed in this examplewe change the type from number to an html string as an examplebut it is not something you usually want to do profiling decorator initiated html wrapper initiated tohtmldecorator called profilingdecorator called inside fib [time elapsed for - fibonacci number for remember that we were able to use class to decorate function because in python everything is an object as long as the object has __call__(methodso it can be used like function nowlet' explore using this property of python in reverse instead of using class to decorate functionlet' use function directly to decorate our fib function function_decorated_ fib py import time def profiling_decorator( )def wrapped_f( )start_time time time(result (nend_time time time(print("[time elapsed for {}{}format(nend_time start_time)return result return wrapped_f @profiling_decorator def fib( )
8,028
decorator pattern print("inside fib"if return fibprev fib for num in range( )fibprevfib fibfib fibprev return fib if __name__ ="__main__" print("fibonacci number for {}{}format(nfib( ))get ready for bit of mind bender the decorator function must return function to be used when the decorated function is called the returned function is used to wrap the decorated function the wrapped_f(function is created when the function is calledso it has access to all the arguments passed to the profiling_decorator(function this technique by which some data (in this casethe function passed to the profiling_ decorator(functiongets attached to code is called closure in python closures let' look at the wrapped_f(function that accesses the non-local variable that is passed in to the profiling_decorator(function as parameter when the wrapped_f(function is createdthe value of the non-local variable is stored and returned as part of the functioneven though the original variable moves out of scope and is removed from the namespace once the program exits the profiling_decorator(function in shortto have closureyou have to have one function returning another function nested within itselfwith the nested function referring to variable within the scope of the enclosing function
8,029
decorator pattern retaining function __name__ and __doc__ attributes as noted beforeyou ideally do not want any function using your decorator to be changed in any waybut the way we implemented the wrapper function in the previous section caused the __name__ and __doc__ attributes of the function to change to that of the wrapped_f(function look at the output of the following script to see how the __name__ attribute changes func_attrs py def dummy_decorator( )def wrap_f()print("function to be decorated" __name__print("nested wrapping function"wrap_f __name__return (return wrap_f @dummy_decorator def do_nothing()print("inside do_nothing"if __name__ ="__main__"print("wrapped function",do_nothing __name__do_nothing(check the following resultsthe wrapped function took on the name of the wrap function wrapped functionwrap_f function to be decorateddo_nothing nested wrapping functionwrap_f inside do_nothing in order to keep the __name__ and __doc__ attributes of the function being wrappedwe must set them to be equal to the function that was passed in before leaving the scope of the decorator function
8,030
decorator pattern def dummy_decorator( )def wrap_f()print("function to be decorated" __name__print("nested wrapping function"wrap_f __name__return (wrap_f __name__ __name__ wrap_f __doc__ wrap_f __doc__ return wrap_f @dummy_decorator def do_nothing()print("inside do_nothing"if __name__ ="__main__"print("wrapped function",do_nothing __name__do_nothing(now there is no longer difference between the do_nothing(function and the decorated do_nothing(function the python standard library includes module that allows retaining the __name__ and __doc__ attributes without setting it ourselves what makes it even better in the context of this is that the module does so by applying decorator to the wrapping function from functools import wraps def dummy_decorator( )@wraps(fdef wrap_f()print("function to be decorated" __name__print("nested wrapping function"wrap_f __name__return (return wrap_f @dummy_decorator def do_nothing()print("inside do_nothing"
8,031
decorator pattern if __name__ ="__main__"print("wrapped function",do_nothing __name__do_nothing(what if we wanted to select the unit that the time should be printed inas in seconds rather than millisecondswe would have to find way to pass arguments to the decorator to do thiswe will use decorator factory firstwe create decorator function thenwe expand it into decorator factory that modifies or replaces the wrapper the factory then returns the updated decorator let' look at our fibonacci code with the functools wrapper included import time from functools import wraps def profiling_decorator( )@wraps(fdef wrap_f( )start_time time time(result (nend_time time time(elapsed_time (end_time start_timeprint("[time elapsed for {}{}format(nelapsed_time)return result return wrap_f @profiling_decorator def fib( )print("inside fib"if return fibprev fib
8,032
decorator pattern for num in range( )fibprevfib fibfib fibprev return fib if __name__ ="__main__" print("fibonacci number for {}{}format(nfib( ))nowlet' extend the code so we can pass in an option to display the elapsed time in either milliseconds or seconds import time from functools import wraps def profiling_decorator_with_unit(unit)def profiling_decorator( )@wraps(fdef wrap_f( )start_time time time(result (nend_time time time(if unit ="seconds"elapsed_time (end_time start_time elseelapsed_time (end_time start_timeprint("[time elapsed for {}{}format(nelapsed_time)return result return wrap_f return profiling_decorator @profiling_decorator_with_unit("seconds"def fib( )print("inside fib"if return
8,033
decorator pattern fibprev fib for num in range( )fibprevfib fibfib fibprev return fib if __name__ ="__main__" print("fibonacci number for {}{}format(nfib( ))as beforewhen the compiler reaches the \@profiling_decorator_with_unit it calls the functionwhich returns the decoratorwhich is then applied to the function being decorated you should also note that once again we used the closure concept to handle parameters passed to the decorator decorating classes if we wanted to profile every method call in specific classour code would look something like thisclass domathstuff(object)@profiling_decorator def fib(self)@profiling_decorator def factorial(self)applying the same method to each method in the class would work perfectly finebut it violates the dry principle (don' repeat yourself what would happen if we decided we were happy with the performance and needed to take the profiling code out of number of sprawling classeswhat if we added methods to the class and forgot to decorate these newly added methodsthere has to be better wayand there is what we want to be able to do is decorate the class and have python know to apply the decoration to each method in the class
8,034
decorator pattern the code we want should look something like this@profile_all_class_methods class domathstuff(object)def fib(self)@profiling_decorator def factorial(self)in essencewhat we want is class that looks exactly like the domathstuff class from the outsidewith the only difference being that every method call should be profiled the profiling code we wrote in the previous section should still be of useso let' take that and make the wrapping function more general so it will work for any function passed to it import time def profiling_wrapper( )@wraps(fdef wrap_f(*args**kwargs)start_time time time(result (*args**kwargsend_time time time(elapsed_time end_time start_time print("[time elapsed for {}{}format(nelapsed_time)return result return wrap_f we received two packed argumentsa list of regular arguments and list of arguments mapped to keywords between themthese two arguments will capture any form of argument that can be passed to python function we also unpack both as we pass them on to the function to be wrapped nowwe want to create class that would wrap class and apply the decorating function to every method in that class and return class that looks no different from the class it received this is achieved through the __getattribute__(magic method python
8,035
decorator pattern uses this method to retrieve methods and attributes for an objectand by overriding this method we can add the decorator as we wanted since __getattribute__(returns methods and valueswe also need to check that the attribute requested is method class_profiler py import time def profiling_wrapper( )@wraps(fdef wrap_f(*args**kwargs)start_time time time(result (*args**kwargsend_time time time(elapsed_time end_time start_time print("[time elapsed for {}{}format(nelapsed_time)return result return wrap_f def profile_all_class_methods(cls)class profiledclass(object)def __init__(self*args**kwargs)self inst cls(*args**kwargsdef __getattribute__(selfs)tryx super(profiledclassself__getattribute__(sexcept attributeerrorpass elsex self inst __getattribute__(sif type( =type(self __init__)return profiling_wrapper(xelsereturn return profiledclass
8,036
decorator pattern @profile_all_class_methods class domathstuff(object)def fib(self)@profiling_decorator def factorial(self)there you have ityou can now decorate both classes and functions it would be helpful to you if you download and read the flask source code (download form the official websiteuse of decorators to handle routing another package that you may find interesting is the django rest framework (form the official websitep arting shots the decorator pattern differs from both the adapter and facade pattern in that the interface does not changebut new functionality is somehow added soif you have specific piece of functionality that you want to attach to number of functions to alter these functions without changing their interfacea decorator may be the way to go exercises extend the fibonacci function wrapper so it also returns the time elapsed in minutes and hoursprinted "hrs:minutes:seconds millisecondsmake list of ten common cases you can think of in which you could implement decorators read the flask source code and write down every interesting use of decorators you come across
8,037
facade pattern the phantom of the opera is thereinside my mind --christine in this we will look at another way to hide the complexity of system from the users of that system all the moving parts should look like single entity to the outside world all systems are more complex than they seem at first glance takefor instancea point of sale (possystem most people only ever interact with such system as customer on the other side of the register in simple caseevery transaction that takes place requires number of things to happen the sale needs to be recordedthe stock levels for each item in the transaction need to be adjustedand you might even have to apply some sort of loyalty points for regular customers most of these systems also allow for specials that take into account the items in the transactionlike buy two and get the cheapest one for free point of sale example there are number of things involved in this transaction processthings like the loyalty systemthe stock systemspecials or promotions systemany payment systemsand whatever else is needed to make the process flow the way it should for each of these interactionswe will have different classes providing the functionality in question (cwessel badenhorst badenhorstpractical python design patterns
8,038
facade pattern it would not be hard to imagine an implementation of the process transaction that would work like thisimport datetime import random class invoice(object)def __init__(selfcustomer)self timestamp datetime datetime now(self number self generate_number(self lines [self total self tax self customer customer def save(self)save the invoice to some sort of persistent storage pass def send_to_printer(self)send invoice representation to external printer pass def add_line(selfinvoice_line)self lines append(invoice_lineself calculate(def remove_line(selfline_item)tryself lines remove(line_itemexcept valueerror as print("could not remove {because there is no such item in the invoiceformat(line_item)def calculate(self)self total sum( total amount for in self linesself tax sum( total tax_rate for in self lines
8,039
facade pattern def generate_number(self)rand random randint( return "{}{}fomat(self timestamprandclass invoiceline(object)def __init__(selfline_item)turn line item into an invoice line containing the current price etc pass def save(self)save invoice line to persistent storage pass class receipt(object)def __init__(selfinvoicepayment_type)self invoice invoice self customer invoice customer self payment_type payment_type pass def save(self)save receipt to persistent storage pass class item(object)def __init__(self)pass @classmethod def fetch(clsitem_barcode)fetch item from persistent storage pass def save(self)save item to persistent storage pass
8,040
facade pattern class customer(object)def __init__(self)pass @classmethod def fetch(clscustomer_code)fetch customer from persistent storage pass def save(self)save customer to persistent storage pass class loyaltyaccount(object)def __init__(self)pass @classmethod def fetch(clscustomer)fetch loyaltyaccount from persistent storage pass def calculate(selfinvoice)calculate the loyalty points received for this purchase pass def save(self)save loyalty account back to persistent storage pass if you want to process saleyou have to interact with all of these classes def complex_sales_processor(customer_codeitem_dict_listpayment_type)customer customer fetch_customer(customer_codeinvoice invoice(for item_dict in item_dict_listitem item fetch(item_dict["barcode"]item amount_in_stock item_dict["amount_purchased"item save(
8,041
facade pattern invoice_line invoiceline(iteminvoice add_line(invoice_lineinvoice calculate(invoice save(loyalt_account loyaltyaccount fetch(customerloyalty_account calculate(invoiceloyalty_account save(receipt receipt(invoicepayment_typereceipt save(as you can seewhatever system is tasked with processing sale needs to interact with very large number of classes specific to the point of sale sub-system systems evolution systems evolve--that is fact of life--and as they grow they can become very complex to keep the whole system simplewe want to hide all the functionality from the client know you smelled it the moment you saw the preceding snippet everything is tightly coupledand we have large number of classes to interact with when we want to extend our pos with some new technology or functionalitywe will need to dig into the internals of the system we might just forget to update some small hidden piece of codeand our whole system will thus come crashing down we want to simplify this system without losing any of the system' power ideallywe want our transaction processor to look something like thisdef nice_sales_processor(customer_codeitem_dict_listpayment_type)invoice someinvoiceclass(customer_codefor item_dict in item_dict_listinvoice add_item(item_dict["barcode"]item_dict_list["amount_ purchased"]invoice finalize(invoice generate_receipt(payment_type
8,042
facade pattern this makes the code much cleaner and easier to read simple rule of thumb in object-oriented programming is that whenever you encounter an ugly or messy systemhide it in an object you can imagine that this problem of complex or ugly systems is one that regularly comes up in the life of programmerso you can be certain that there are several opinions on how to best solve this issue one such the solution is to use design pattern called the facade pattern this pattern is specifically used to create complexity-limiting interface to sub-system or collection of sub-systems look at the following piece of code to get better feel for how this abstraction via the facade pattern should happen simple_ facade py class invoicedef __init__(selfcustomer)pass class customeraltered customer class to try to fetch customer on init or creates new one def __init__(selfcustomer_id)pass class itemaltered item class to try to fetch an item on init or creates new one def __init__(selfitem_barcode)pass class facade@staticmethod def make_invoice(customer)return invoice(customer@staticmethod def make_customer(customer_id)return customer(customer_id@staticmethod def make_item(item_barcode)return item(item_barcodebefore you read ontry to implement facade pattern for the pos system on your own
8,043
facade pattern what sets the facade pattern apart one key distinction with regards to the facade pattern is that the facade is used not just to encapsulate single object but also to provide wrapper that presents simplified interface to group of complex sub-systems that is easy to use without unneeded functions or complexity whenever possibleyou want to limit the amount of knowledge and or complexity you expose to the world outside the system the more you allow access to and interaction with systemthe more tightly coupled that system becomes the ultimate result of allowing greater depth of access to your system is system that can be used like black boxwith clear set of expected inputs and well-defined outputs the facade should decide which internal classes and representations to use it is also within the facade that you will make changes in terms of functions to be assigned to external or updated internal systems when the time comes to do so facades are often used in software libraries since the convenient methods provided by the facade make the library easier to understand and use since interaction with the library happens via the facadeusing facades also reduces the dependencies from outside the library on its inner workings as for any other systemthis allows more flexibility when developing the library not all apis are created equaland you will have to deal with poorly designed collections of apis howeverusing the facade patternyou can wrap these apis in single well-designed api that is joy to work with one of the most useful habits you can develop is that of creating solutions to your own problems if you have system you need to work with that is less than idealbuild facade for it to make it work in your context if your ide misses tool you lovecode up your own extension to provide this function stop waiting for other people to come along and provide solution you will feel more empowered every day that you take an action to shape your world to fit your needs let' implement our pos backend as just such facade since we do not want to build the whole systemseveral the functions defined will be stubswhich you could expand if you chose to class sale(object)def __init__(self)pass
8,044
facade pattern @staticmethod def make_invoice(customer_id)return invoice(customer fetch(customer_id)@staticmethod def make_customer()return customer(@staticmethod def make_item(item_barcode)return item(item_barcode@staticmethod def make_invoice_line(item)return invoiceline(item@staticmethod def make_receipt(invoicepayment_type)return receipt(invoicepayment_type@staticmethod def make_loyalty_account(customer)return loyaltyaccount(customer@staticmethod def fetch_invoice(invoice_id)return invoice(customer@staticmethod def fetch_customer(customer_id)return customer(customer_id@staticmethod def fetch_item(item_barcode)return item(item_barcode@staticmethod def fetch_invoice_line(line_item_id)return invoiceline(item
8,045
facade pattern @staticmethod def fetch_receipts(invoice_id)return receipt(invoicepayment_type@staticmethod def fetch_loyalty_account(customer_id)return loyaltyaccount(customer@staticmethod def add_item(invoiceitem_barcodeamount_purchased)item item fetch(item_barcodeitem amount_in_stock amount_purchased item save(invoice_line invoiceline make(iteminvoice add_line(invoice_line@staticmethod def finalize(invoice)invoice calculate(invoice save(loyalt_account loyaltyaccount fetch(invoice customerloyalty_account calculate(invoiceloyalty_account save(@staticmethod def generate_receipt(invoicepayment_type)receipt receipt(invoicepayment_typereceipt save(using this new sales classwhich serves as facade for the rest of the systemthe ideal function we looked at earlier now looks like thisdef nice_sales_processor(customer_iditem_dict_listpayment_type)invoice sale make_invoice(customer_idfor item_dict in item_dict_listsale add_item(invoiceitem_dict["barcode"]item_dict_list["amount_ purchased"]
8,046
facade pattern sale finalize(invoicesale generate_receipt(invoicepayment_typeas you can seenot lot has changed the code for sales results in single entry point to the more complex business system we now have limited set of functions to call via the facade that allows us to interact with the parts of the system we need access towithout overburdening us with all the internals of the system we also have single class to interact withso we no longer have to go digging through the whole class diagram to find the correct place to hook into the system in the sub-systema third-party stock-management system or loyalty program could replace internal systems without having the clients using the facade class change single line of code our code is thus more loosely coupled and easier to extend the pos clients do not care if we decide to hand off the stock and accounting to third-party provider or build and run an internal system the simplified interface remains blissfully unaware of the complexity under the hood without reducing the power inherent in the sub-system arting shots there is not much to the facade pattern you start out by feeling the frustration of subsystem or group of sub-systems that does not work the way you want it toor you find yourself having to look up interactions in many classes by nowyou know something is not rightso you decide to clean up this messor at least hide it behind singleelegant interface you design your wrapper class to turn the ugly sub-system into black box that deals with the interactions and complexities for you the rest of your codeand other potential client codeonly deals with this facade the world is now just tiny bit better for your efforts--well done exercises facades are often implemented as singletons when they do not have to keep track of state alter the facade implementation in the last section of code so it uses the singleton pattern from expand the point of sale system outlined in this until you have system that you could use in the real world pick your favorite social media platform and create your own facade that allows you to interact with their api
8,047
proxy pattern do you bite your thumb at ussir--abramromeo and juliet as programs growyou often find that there are functions that you call very often when these calculations are heavy or slowyour whole program suffers consider the following example for calculating the fibonacci sequence for number ndef fib( )if return return fib( fib( this fairly simple recursive function has serious flawespecially as becomes really large can you figure out what the problem might beif you thought that it is the fact that the value of some (xwould have to be calculated multiple times whenever you want to calculate fibonacci number for an larger than you are spot on there are multiple ways we could handle this problembut want to use very specific waycalled memoization emoization whenever we have function being called multiple timeswith the value repeatedit would be useful to store the response of the calculation so we do not have to go through the process of calculating the value againwe would rather just grab the value we already calculated and return that this act of saving the result of function call for later use is called memoization (cwessel badenhorst badenhorstpractical python design patterns
8,048
proxy pattern nowlet' see what effect memoization would have on our simple example case import time def fib( )if return return fib( fib( if __name__ ="__main__"start_time time time(fib_sequence [fib(xfor in range( , )end_time time time(print"calculating the list of {fibonacci numbers took {secondsformatlen(fib_sequence)end_time start_time let this run for some timesee the amount of time elapsed just to calculate fibonacci numbers from to on my computeri got the following resultcalculating the list of fibonacci numbers took seconds some new systems laugh at mere fibonacci numbers if you are in that situationyou could try increasing the numbers in orders of magnitude-- --until you hit upon number that shows load without taking forever to complete use this number throughout the rest of the if we were to cache the results of each callhow would that affect the calculationlet' implement the same function as beforebut this time we will make use of an extra dictionary to keep track of requests we have calculated before
8,049
proxy pattern import time def fib_cached (ncache)if return if in cachereturn cache[ncache[nfib_cached ( cachefib_cached ( cachereturn cache[nif __name__ ="__main__"cache {start_time time time(fib_sequence [fib_cached (xcachefor in range( )end_time time time(print"calculating the list of {fibonacci numbers took {secondsformatlen(fib_sequence)end_time start_time run this code on my machinethe same series of calculations now gives the following outputcalculating the list of fibonacci numbers took - seconds
8,050
proxy pattern this is such good result that we want to create calculator object that does several mathematical series calculationsincluding calculating the fibonacci numbers see hereclass calculator(object)def fib_cached(selfncache)if return tryresult cache[nexceptcache[nfib_cached( cachefib_cached( cacheresult cache[nreturn result you know that most users of your object will not know what they should do with the cache variableor what it means having this variable in your method definition for the calculator method might cause confusion what you want instead is to have method definition that looks like the first piece of code we looked atbut with the performance benefits of caching in an ideal situationwe would have class that functions as an interface to the calculator class the client should not be aware of this classin that the client only codes toward the interface of the original classwith the proxy providing the same functionality and results as the original class the proxy pattern proxy provides the same interface as the original objectbut it controls access to the original object as part of this controlit can perform other tasks before and after the original object is accessed this is especially helpful when we want to implement something like memoization without placing any responsibility on the client to understand caching by shielding the client from the call to the fib methodthe proxy allows us to return the calculated result
8,051
proxy pattern duck typing allows us to create such proxy by copying the object interface and then using the proxy class instead of the original class import time class rawcalculator(object)def fib(selfn)if return return self fib( self fib( def memoize(fn)__cache {def memoized(*args)key (fn __name__argsif key in __cachereturn __cache[key__cache[keyfn(*argsreturn __cache[keyreturn memoized class calculatorproxy(object)def __init__(selftarget)self target target fib getattr(self target'fib'setattr(self target'fib'memoize(fib)def __getattr__(selfname)return getattr(self targetname
8,052
proxy pattern if __name__ ="__main__"calculator calculatorproxy(rawcalculator()start_time time time(fib_sequence [calculator fib(xfor in range( )end_time time time(print"calculating the list of {fibonacci numbers took {secondsformatlen(fib_sequence)end_time start_time must admitthis is not trivial piece of codebut let' step through it and see what is happening firstwe have the rawcalculator classwhich is our imagined calculation object at the momentit only contains the fibonacci calculationbut you could imagine it containing many other recursively defined series and sequences as beforethis method uses recursive call nextwe define closure that wraps the function callbut let' leave that for later finallywe have the calculatorproxy classwhich upon initialization takes the target object as parametersets an attribute on the proxy objectand then proceeds to override the fib method of the target object with memoized version of the fib method whenever the target object calls its fib(methodthe memoized version gets called nowthe memoize function takes function as parameter nextit initializes an empty dictionary we then define function that takes list of argumentsgets the name of the function passed to itand creates tuple containing the function name and received arguments this tuple then forms the key to the __cache dictionary the value represents the value returned by the function call the memoized function first checks if the key is already in the cache dictionary if it isthere is no need to recalculate the valueand the value is returned if the key is not foundthe original function is calledand the value is added to the dictionary before it is returned
8,053
proxy pattern the memoize function takes regular old function as parameterthen it records the result of calling the received function if needed it calls the function and receives the newly calculated values before returning new function with the result saved if that value should be needed in future the final result is seen herecalculating the list of fibonacci numbers took - seconds really like the fact that the memoize function can be used with any function passed to it having generic piece of code like this is helpfulas it allows you to memoize many different functions without altering the code this is one of the main aims of objectoriented programming as you gain experienceyou should also build up library of interesting and useful pieces of code you can reuse ideallyyou want to package these into your own libraries so you can do more in less time it also helps you to keep improving now that you understand the proxy patternlet' look at the different types of proxies available to us we already looked at cache proxy in detailso what remains are the followingremote proxy virtual proxy protection proxy remote proxy when we want to abstract the location of an objectwe can use remote proxy the remote object appears to be local resource to the client when you call method on the proxyit transfers the call to the remote object once the result is returnedthe proxy makes this result available to the local object virtual proxy sometimes objects may be expensive to createand they may not be needed until later in the program' execution when it is helpful to delay object creationa proxy can be used the target object can then be created only once it is needed
8,054
proxy pattern protection proxy many programs have different user roles with different levels of access by placing proxy between the target object and the client objectyou can restrict access to information and methods on the target object parting shots you saw how proxy could take many formsfrom the cache proxy we dealt with in this to the network connection whenever we want to control how an object or resource is accessed in way that is transparent from the client' perspectivethe proxy pattern should be considered in this you saw how the proxy pattern wraps other objects and alters the way they execute in way that is invisible to the user of these functionssince they still take the same parameters as input and returns the same results as output the proxy pattern typically has three partsthe client that requires access to some object the object the client wants to access the proxy that controls access to the object the client instantiates the proxy and makes calls to the proxy as if it were the object itself because python is dynamically typedwe are not concerned with defining some common interface or abstract classsince we are only required to provide the same attributes as the target object in order for the proxy to be treated exactly like the target object by the client code it is helpful to think about proxies in terms we are already familiar withlike web proxy once connected to the proxyyouthe clientare not aware of the proxyyou can access the internet and other network resources as if there were no proxy this is the key differentiator between the proxy pattern and the adapter pattern with the proxy patternyou want the interface to remain constantwith some actions taking place in the background converselythe adapter pattern is targeted at changing the interface
8,055
proxy pattern exercises add more functions to the rawcalculator class so it can create other sequences expand the calculatorproxy class to handle the new series-generation functions you added do they also use the memoize function out of the boxalter the __init__(function to iterate over the attributes of the target object and automatically memoize the callable attributes count how many times each of the rawcalculator methods is called during programuse this to calculate how many calls are made to the fib(method check the python standard library for other ways to memoize functions
8,056
chain of responsibility pattern it wasn' me --shaggy"it wasn' meweb apps are complex beasts they need to interpret incoming requests and decide what should be done with them when you think about creating framework to help you build web apps more quicklyyou stand very real chance of drowning in the complexity and options involved with such project python is home to many web framework since the language is popular among developers of cloud applications in this we are going to explore one component of web frameworks called the middleware layer the middleware sits in the middlebetween the client making requests of the app and the actual application it is layer that both the requests from the client and the responses from the main application functions need to pass through in the middlewareyou can do things like log incoming requests for troubleshooting you can also add some code to capture and save the response from the app that goes back to the user oftenyou will find code to check the user' access and whether they should be allowed to execute the request they are making on the system you might want to translate the incoming request body into data format that is easy to handleor escape all input values to protect the system from hackers injecting code into the app you could also think of the routing mechanism of the app as part of the middleware the routing mechanism determines what code should be used to respond to requests directed at specific endpoint (cwessel badenhorst badenhorstpractical python design patterns
8,057
chain of responsibility pattern most web frameworks create request object that is used throughout the system simple request object might look like thisclass request(object)def __init__(selfheadersurlbodygetpost)self headers self url self body self get self post at the momentyou have no extra functionality associated with the requestbut this limited object should be good start for you to build up some intuition about the way middleware is used in handling client requests to web app web frameworks need to return some sort of response to the client let' define basic response objectclass response(object)def __init__(selfheadersstatus_codebody)self headers self status_code self body if you look at the documentation of one of the more popular frameworkslike django or flaskyou will see that the objects are way more involved that the simple ones just definedbut these will serve our purpose one of the things we would like our middleware to do is check for token in the request object' headers and then add the user object to the object this will allow the main app to access the currently logged-in user to alter the interface and information displayed as needed let' write basic function that will grab the user token and load user object from database the function will then return user object that can be attached to the request object import user def get_user_object(usernamepassword)return user find_by_token(usernamepassword
8,058
chain of responsibility pattern you could easily create user class that gets stored in database as an exerciselook at the sqlalchemy project (an sqlite database where you store basic user data make sure the user class has class function that finds user based on the user token fieldwhich is unique setting up wsgi server let' make this little more practical since you already have pip running on your systeminstall uwsgi on your virtual environmentpip install uwsgi windows users might receive an error messageattributeerrormodule 'oshas no attribute 'uname'for this and in you will need to install cygwin make sure to select the python interpreterpip gcc-corepython -devel (check that you select your windows version- -bit/ -bit)libcrypt-develand wget from the options during the cygwin install process you can get it at install html cygwin is linux-like terminal for windows you can navigate using default linux commandssuch as the pip install uwsgi command you could also follow the virtualenv setup instructions from to set up virtual environment in cygwin (the activate command is located in yourenvnamescriptsif all of this seems like way too much effortyou would do well to install virtualbox and run ubuntu on the box thenyou can follow the linux path completelywithout any changes in your day-to-day environment let' test that the server works and can serve up websites on your machine the following script returns very simple status success and hello world message in the body (from the uwsgi documentation at latest/wsgiquickstart htmlhello_world_server py def application(envstart_response)start_response(' ok'[('content-type','text/html')]return [ "hello world"
8,059
chain of responsibility pattern in your command linewith the virtual environment activestart the serverwith hello_world_server py set as the application to handle requests uwsgi --http : --wsgi-file hello_world_server py if you point your browser to hello world in the window congratulationsyou have your very own web server runningyou could even deploy it on serverpoint url at itand let the world send requests to it what we want to do next is see how the middleware fits into the flow from request to response by building it from the ground up since the server is already up and runninglet' add function to check if the user token is set in the headers we are going to follow convention that is used by number of bigger apis you might find online uthentication headers the idea is that the client includes an authorization headerwhere the header value is set to the word basic followed by spacefollowed by base -encoded string the string that gets encoded has the following formusername:passwordwhich will be used to identify and verify the user on the system before we continue building up the functionalityit is important to note that by including the authentication header whenever you make call to the appand having the app check for the authorization headeryou remove the need for the app to keep track of which user is making the callsand instead you get to attach the user to the request when that request happens the easiest way to test url endpoints is to install tool like postman on your system it allows you to request urls from the app and interpret the results the free postman app can be downloaded hereonce the postman install concludesopen the app firstenter the same url you entered in your browser into the postman address bar and click send or press enter you should see hello world in the box at the bottom of the screen this tells you that postman is working and your app is still running
8,060
chain of responsibility pattern right below the address baryou will see box with couple of tabs attached to it one of these tabs is authorization click it and select basic auth from the dropdown box now username and password fields are added to the interface postman allows you to enter the username and password in these boxesand it will then encode the string for you to see what the request object you receive from uwsgi looks likeyou need to change the script you used to return the hello world message to the browser hello_world_request_display py import pprint pp pprint prettyprinter(indent= def application(envstart_response)pp pprint(envstart_response(' ok'[('content-type','text/html')]return [ "hello world "the pprint module included in the python standard library prints data types like dictionaries and lists and is an easy-to-read format it is valuable tool when you are debugging complex datatypeslike the request received from web server when you restart your uwsgi server and send with postman the request including the authorization headersyou will see dictionary printed in the console one of the keys in the dictionary will be http_authorizationwhich is the field containing the word basic followed by spacefollowed by base -encoded string to retrieve the user object from the databasethis string needs to be decoded and then split into the username and password respectively we can do all of this by updating the server application we will begin by obtaining the value of the http_authorization header thenwe will split that value on spacegiving us the word basic and the base -encoded string we will then proceed to decode the string and split on the :which will result in an array with the username at index and the password for the user
8,061
chain of responsibility pattern at index we will then send this to simple function that returns user objectwhich we just construct inline for the sake of this examplebut you are welcome to plug in your function that gets user from your local sqlite database user_aware_server py import base class user(object)def __init__(selfusernamepasswordnameemail)self username username self password password self name name self email email @classmethod def get_verified_user(clsusernamepassword)return userusernamepasswordusername"{}@demo comformat(usernamedef application(envstart_response)authorization_header env["http_authorization"header_array authorization_header split(encoded_string header_array[ decoded_string base decode(encoded_stringdecode('utf- 'usernamepassword decoded_string split(":"user user get_verified_user(usernamepasswordstart_response(' ok'[('content-type''text/html')]response "hello {}!format(user namereturn [response encode('utf- ')
8,062
chain of responsibility pattern in our examplewe created user based on the request this is clearly not correctbut the fact that we separated it into its own class allows us to take the code and change the get_verified_user method to get the user based on username we then verify that the password for that user is correct thenyou might want to add some code to handle the instance where the user does not exist in the database at this timewe already see lot of code relevant only to the process of checking user credentials in the main server application this feels wrong let' emphasize just how wrong it is by adding the most basic routing code possible our router will look for headerwhich tells us which endpoint was requested by the client based on this informationwe will print hello message for all casesexcept if the path contains the substring goodbyein which case the server will return goodbye message when we print out the request contentswe see that the path information is captured in the path_info header the header starts with leading "/followed by the rest of the path you can split the path on "/and then check if the path contains the word goodbye import base from pprint import prettyprinter pp prettyprinter(indent= class user(object)def __init__(selfusernamepasswordnameemail)self username username self password password self name name self email email @classmethod def get_verified_user(clsusernamepassword)return userusernamepasswordusername"{}@demo comformat(username
8,063
chain of responsibility pattern def application(envstart_response)authorization_header env["http_authorization"header_array authorization_header split(encoded_string header_array[ decoded_string base decode(encoded_stringdecode('utf- 'usernamepassword decoded_string split(":"user user get_verified_user(usernamepasswordstart_response(' ok'[('content-type''text/html')]path env["path_info"split("/"if "goodbyein pathresponse "goodbye {}!format(user nameelseresponse "hello {}!format(user namereturn [response encode('utf- ') ' sure your code sense is making lot of noise right now the application function is clearly doing three different things right now it starts out getting the user object thenit decides what endpoint the client is requesting and composes the relevant message based on that path lastlyit returns the encoded message to the client who made the request whenever more functionality is required between the initial request from the user and the actual responsethe application function becomes more complex in shortyour code is bound to become mess if you continue down this path we want each function to ideally do one and only one thing the chain of responsibility pattern the idea that every piece of code does one thing and only one thing is called the single responsibility principlewhich is another handy guideline when you are working on writing better code
8,064
chain of responsibility pattern if we wanted to adhere to the single responsibility principle in the preceding examplewe would need piece of code to handle the user retrieval and another piece of code to validate that the user matches the password yet another piece of code would generate message based on the path of the requestandfinallysome piece of code would return the response to the browser before we attempt to write the code for the serverwe will build up some intuition about the solution using sample application in our sample applicationwe have four functionseach of which simply prints out message def function_ ()print("function_ "def function_ ()print("function_ "def function_ ()print("function_ "def function_ ()print("function_ "def main_function()function_ (function_ (function_ (function_ (if __name__ ="__main__"main_function(from our discussion in the beginning of this sectionwe know that it is not ideal to have the main_function call each of the functions in ordersince in real-world scenario this leads to the messy code we encountered in the previous section
8,065
chain of responsibility pattern what we want is to create some sort of way for us to make single call and then have the functions called dynamically class catchall(object)def __init__(self)self next_to_execute none def execute(self)print("end reached "class function class(object)def __init__(self)self next_to_execute catchall(def execute(self)print("function_ "self next_to_execute execute(class function class(object)def __init__(self)self next_to_execute catchall(def execute(self)print("function_ "self next_to_execute execute(class function class(object)def __init__(self)self next_to_execute catchall(def execute(self)print("function_ "self next_to_execute execute(class function class(object)def __init__(self)self next_to_execute catchall(def execute(self)print("function_ "self next_to_execute execute(
8,066
chain of responsibility pattern def main_function(head)head execute(if __name__ ="__main__"hd function class(current hd current next_to_execute function class(current current next_to_execute current next_to_execute function class(current current next_to_execute current next_to_execute function class(main_function(hdeven though the amount of code written is significantly more than in the first instanceyou should begin to see how cleanly this new program separates the execution of each function from the others to illustrate this furtherwe now extend the main execute function to include request string the string is series of digitsand if the digit from the function name is included in the digit stringthe function prints its name together with the request string before it removes all instances of the digit in question from the request string and passes the request on to the rest of the code for processing in our original contextwe could solve this new requirement as followsdef function_ (in_string)print(in_stringreturn "join([ for in in_string if !' ']def function_ (in_string)print(in_stringreturn "join([ for in in_string if !' ']def function_ (in_string)print(in_stringreturn "join([ for in in_string if !' ']
8,067
chain of responsibility pattern def function_ (in_string)print(in_stringreturn "join([ for in in_string if !' ']def main_function(input_string)if ' in input_stringinput_string function_ (input_stringif ' in input_stringinput_string function_ (input_stringif ' in input_stringinput_string function_ (input_stringif ' in input_stringinput_string function_ (input_stringprint(input_stringif __name__ ="__main__"main_function(" "yesyou are right--all the functions do exactly the same thingbut this is just because of the way the sample problem is set up if you were to refer to the original problemyou would see that this is not always the case what should also feel off is the series of if statements that will only grow in length as more functions are added to the execution queue finallyyou may have noted how closely coupled the main_function is to each of the functions being executed implementing chain of responsibility in our project nowlet' solve the same problem using the idea we began to build earlier class catchall(object)def __init__(self)self next_to_execute none def execute(selfrequest)print(request
8,068
chain of responsibility pattern class function class(object)def __init__(self)self next_to_execute catchall(def execute(selfrequest)print(requestrequest "join([ for in request if !' ']self next_to_execute execute(requestclass function class(object)def __init__(self)self next_to_execute catchall(def execute(selfrequest)print(requestrequest "join([ for in request if !' ']self next_to_execute execute(requestclass function class(object)def __init__(self)self next_to_execute catchall(def execute(selfrequest)print(requestrequest "join([ for in request if !' ']self next_to_execute execute(requestclass function class(object)def __init__(self)self next_to_execute catchall(def execute(selfrequest)print(requestrequest "join([ for in request if !' ']self next_to_execute execute(request
8,069
chain of responsibility pattern def main_function(headrequest)head execute(requestif __name__ ="__main__"hd function class(current hd current next_to_execute function class(current current next_to_execute current next_to_execute function class(current current next_to_execute current next_to_execute function class(main_function(hd" "already it is clear that we have much cleaner solution at hand we did not have to make any changes to the way each class is connected to the nextand apart from passing on the requestwe did not require any changes to be made to the individual execute functions or the main function in order to accommodate the way each class executes the request we have clearly separated each function into its own unit of code that can be plugged intoor removed fromthe chain of classes dealing with the request each handler cares only about its own execution and ignores what happens when another handler executes because of the query the handler decides in the moment if it should do anything as result of the request it receiveswhich leads to increased flexibility in determining which handlers should execute as result of query the best part of this implementation is that handlers can be added and removed at runtimeand when the order is unimportant in terms of the execution queueyou could even shuffle the order of the handlers this only goes to showonce againthat loosely coupled code is more flexible than tightly coupled code
8,070
chain of responsibility pattern to further illustrate this flexibilitywe extend the previous program so each class will only do something if it sees that the digit associated with the class name is in the request string class catchall(object)def __init__(self)self next_to_execute none def execute(selfrequest)print(requestclass function class(object)def __init__(self)self next_to_execute catchall(def execute(selfrequest)if ' in requestprint("executing type function class with request [{}]format(request)request "join([ for in request if !' ']self next_to_execute execute(requestclass function class(object)def __init__(self)self next_to_execute catchall(def execute(selfrequest)if ' in requestprint("executing type function class with request [{}]format(request)request "join([ for in request if !' ']self next_to_execute execute(requestclass function class(object)def __init__(self)self next_to_execute catchall(
8,071
chain of responsibility pattern def execute(selfrequest)if ' in requestprint("executing type function class with request [{}]format(request)request "join([ for in request if !' ']self next_to_execute execute(requestclass function class(object)def __init__(self)self next_to_execute catchall(def execute(selfrequest)if ' in requestprint("executing type function class with request [{}]format(request)request "join([ for in request if !' ']self next_to_execute execute(requestdef main_function(headrequest)head execute(requestif __name__ ="__main__"hd function class(current hd current next_to_execute function class(current current next_to_execute current next_to_execute function class(current current next_to_execute current next_to_execute function class(main_function(hd" "
8,072
chain of responsibility pattern note that this time we do not have any digits in the requestand as result the code for the instance of function class is not executed before the request is passed on to the instance of function class alsonote that we had no change in the code for the setup of the execution chain or in main_function this chain of handlers is the essence of the chain of responsibility pattern  more pythonic implementation in the classic implementation of this patternyou would define some sort of generic handler type that would define the concept of the next_to_execute object as well as the execute function as we have seen beforethe duck-typing system in python frees us from having to add the extra overhead as long as we define the relevant parts for each handler we want to use in the chainwe do not need to inherit from some shared base this not only saves lot of time otherwise spent writing boilerplate codebut also enables youthe developerto easily evolve these types of ideas as your application or system calls for it in more constrained languagesyou do not have the luxury of evolving the design on the fly changing direction like this often requires large redesignwith lot of code requiring rewrite to avoid the pain of redesigning the whole system or rebuilding large parts of the applicationengineers and developers try to cater to every eventuality they can dream up this approach is flawed in two critical ways firsthuman knowledge of the future is imperfectso even if you were to design the perfect system for today ( near impossibility)it would be impossible to account for every way in which clients might use your systemor for where the market might drive your application the second is thatfor the most partyou ain' gonna need it (yagni)orstated differentlymost of the potential futures that get covered in the design of such system will never be neededand as such it is time and effort that has gone to waste once againpython provides the capability to start with simple solution to simple problem and then grow the solution as the use cases change and evolve python moves with youchanging and growing as you do much like the game of gopython is easy to pick upbut you can devote lifetime to mastering its many possibilities
8,073
chain of responsibility pattern here is simple implementation of the chain of responsibility patternwith all of the extras stripped away all that is left is the general structure that we will be implementing on our web app class endhandler(object)def __init__(self)pass def handle_request(selfrequest)pass class handler (object)def __init__(self)self next_handler endhandler(def handle_request(selfrequest)self next_handler handle_request(requestdef main(request)concrete_handler handler (concrete_handler handle_request(requestif __name__ ="__main__"from the command line we can define some request main(requestwe will now use this very minimal skeleton to significantly improve our web app from the beginning of this the new solution will adhere to the single responsibility principle much more closely you will also note that you could add many more functions and extensions to the process import base class user(object)def __init__(selfusernamepasswordnameemail)self username username self password password
8,074
chain of responsibility pattern self name name self email email @classmethod def get_verified_user(clsusernamepassword)return userusernamepasswordusername"{}@demo comformat(usernameclass endhandler(object)def __init__(self)pass def handle_request(selfrequestresponse=none)return response encode('utf- 'class authorizationhandler(object)def __init__(self)self next_handler endhandler(def handle_request(selfrequestresponse=none)authorization_header request["http_authorization"header_array authorization_header split(encoded_string header_array[ decoded_string base decode(encoded_stringdecode('utf- 'usernamepassword decoded_string split(":"request['username'username request['password'password return self next_handler handle_request(requestresponseclass userhandler(object)def __init__(self)self next_handler endhandler(
8,075
chain of responsibility pattern def handle_request(selfrequestresponse=none)user user get_verified_user(request['username']request['password']request['user'user return self next_handler handle_request(requestresponseclass pathhandler(object)def __init__(self)self next_handler endhandler(def handle_request(selfrequestresponse=none)path request["path_info"split("/"if "goodbyein pathresponse "goodbye {}!format(request['user'nameelseresponse "hello {}!format(request['user'namereturn self next_handler handle_request(requestresponsedef application(envstart_response)head authorizationhandler(current head current next_handler userhandler(current current next_handler current next_handler pathhandler(start_response(' ok'[('content-type''text/html')]return [head handle_request(env)another alternative implementation of the chain of responsibility pattern is to instantiate main object to dispatch handlers from list passed into the dispatcher on instantiation
8,076
chain of responsibility pattern class dispatcher(object)def __init__(selfhandlers=[])self handlers handlers def handle_request(selfrequest)for handler in self handlersrequest handler(requestreturn request the dispatcher class takes advantage of the fact that everything in python is an objectincluding functions since functions are first-class citizens (which means they can be passed to function and be returned from functionwe can instantiate the dispatcher and pass in list of functionswhich can be saved like any other list when the time comes to execute the functionswe iterate over the list and execute each function in turn implementing the sample code we have been using in this section using the dispatcher looks like thisclass dispatcher(object)def __init__(selfhandlers=[])self handlers handlers def handle_request(selfrequest)for handle in self handlersrequest handle(requestreturn request def function_ (in_string)print(in_stringreturn "join([ for in in_string if !' ']def function_ (in_string)print(in_stringreturn "join([ for in in_string if !' ']
8,077
chain of responsibility pattern def function_ (in_string)print(in_stringreturn "join([ for in in_string if !' ']def function_ (in_string)print(in_stringreturn "join([ for in in_string if !' ']def main(request)dispatcher dispatcher(function_ function_ function_ function_ ]dispatcher handle_request(requestif __name__ ="__main__"main(" "as an exercisei suggest you use this structure to implement the process for the web app before we wrap up this want you to think about the discussion on middleware that we started with can you see how you would use the chain of responsibility pattern to implement middleware for your web app by adding handlers to the queueparting shots as we have seen throughout this the request is the central object around which the pattern is builtand as such care should be taken when constructing and altering the request object as it gets passed from one handler to the next since the chain of responsibility pattern affords us the opportunity to shuffle and alter the handlers used at runtimewe can apply some performance-enhancing ideas to the chain we could move handler to the front of the chain every time it is usedresulting in more regularly used handlers taking the early positions in the chain followed
8,078
chain of responsibility pattern by the less frequently used handlers (use this only when the order of execution of the handlers does not matterwhen the order of the handlers has some sort of meaningyou could get some improved performance using ideas from the previous and caching the results of certain handled requests we never want to completely ignore requestso you must make sure to have some sort of end handler serving as catch-all for the chain toat the very leastalert you that the request was not handled by any of the handlers in your chain in the examples from this we had the chain execute until all the handlers had look at the request this does not have to be the caseyou can break the chain at any point and return result the chain of responsibility pattern can serve to encapsulate processing of elements into pipeline (like data pipelinefinallya good rule of thumb is to use the chain of responsibility pattern wherever you have more than one potential handler for requestand thus do not know beforehand which handler or handlers would best handle the requests you will receive exercises look at sqlalchemy and create an interface to an sqlite database where you store basic user data expand the user class function that retrieves the user so it uses the sqlite databaseas in the previous exercise add the logger you built in on the singleton patternto the chain of responsibility of your web application so you can log the incoming request and the responses sent back to the client implement your web app from this using the dispatcher implementation of the chain of responsibility
8,079
command pattern 'll be back --terminator the robots are coming in this we are going to look at how we can control robot using python code for our purposeswe will be using the turtle module included in the python standard library this will allow us to handle commands like move forwardturn leftand turn right without the need to build an actual robotalthough you should be able to use the code developed in this combined with board like the raspberry pi and some actuatorsto actually build robot you could control with code ontrolling the turtle let' begin by doing something simplelike drawing square on the screen using the turtle module turtle_basic py import turtle turtle color('blue''red'turtle begin_fill(for in range( )turtle forward( turtle left( turtle end_fill(turtle done((cwessel badenhorst badenhorstpractical python design patterns
8,080
command pattern the turtle is simple line-and-fill tool that helps to visualize what the robot is doing in the preceding codewe import the turtle library nextwe set the line color to blue and the background color to red thenwe tell the turtle to record the current point as the start of polygon that will be filled later thenthe loop draws the four sides of the square finallythe end_fill(method fills the polygon with red the done(method keeps the program from terminating and closing the window once the process is completed if you are using an ubuntu system and get an error message regarding python -tkyou need to install the package sudo apt-get install python -tk run the codeand you should see little triangle (the turtlemove on the screen this approach works while we are trying to draw shapes and lines on the screenbut since the turtle is just metaphor for our robotdrawing pretty shapes does not have lot of use we are going to extend our robot control script to accept four commands (startstopturn left degreesand turn right degrees)which we will map to keyboard keys turtle_control py import turtle turtle setup( screen turtle screen(screen title("keyboard drawing!" turtle turtle(distance def advance() forward(distancedef turn_left() left( def turn_right() right(
8,081
command pattern def retreat() backward( def quit()screen bye(screen onkey(advance" "screen onkey(turn_left" "screen onkey(turn_right" "screen onkey(retreat" "screen onkey(quit"escape"screen listen(screen mainloop(what you are essentially doing is creating an interface with which to control the turtle in the real worldthis would be akin to remote control car that takes one signal to mean turn leftanother for turn righta third for accelerateand fourth for decelerate if you were to build an rc sender that translated the signals that usually come from the remote to now take input from keyboard using some electronics and your usb portyou would be able to use code similar to the code we have here to control the remote control car in the same wayyou could control robot via remote control in essencewe are sending commands from one part of our system to another the command pattern whenever you want to send an instruction or set of instructions from one object to anotherwhile keeping these objects loosely coupledit is wise to encapsulate everything needed to execute the instructions in some kind of data structure the client that initiates the execution does not have to know anything about the way in which the instruction will be executedall it is required to do is to set up all the required information and hand off whatever needs to happen next to the system since we are dealing with an object-oriented paradigmthe data structure used to encapsulate the instruction will be an object the class of objects used to encapsulate information needed by some other method in order to execute is called command the client object instantiates command containing the method it wishes to executealong
8,082
command pattern with all the parameters needed to execute the methodas well as some target object that has the method this target object is called the receiver the receiver is an instance of class that can execute the method given the encapsulated information all of this relies on an object called an invoker that decides when the method on the receiver will execute it might help to realize that invocations of methods are similar to instances of classes without any actual functionalitythe command pattern can be implemented like thisclass commanddef __init__(selfreceivertext)self receiver receiver self text text def execute(self)self receiver print_message(self textclass receiver(object)def print_message(selftext)print("message received{}format(text)class invoker(object)def __init__(self)self commands [def add_command(selfcommand)self commands append(commanddef run(self)for command in self commandscommand execute(if __name__ ="__main__"receiver receiver(command command(receiver"execute command "command command(receiver"execute command "
8,083
command pattern invoker invoker(invoker add_command(command invoker add_command(command invoker run(now you would be able to queue up commands to be executed even if the receiver were busy executing another command this is very useful concept in distributed systems where incoming commands need to be captured and handledbut the system may be busy with another action having all the information in an object in the queue allows the system to deal with all incoming commands without losing important commands while executing some other command you essentially get to dynamically create new behavior at runtime this process is especially useful when you want to set up the execution of method at one time and then sometime later execute it think about the implication for robot like the mars rover if operatives were only able to send single command to be executed and then had to wait for the command to finish execution before they could transmit the next command it would make doing anything on mars extremely time-consuming to the point of being impossible what can be done instead is to send sequence of actions to the rover the rover can then invoke each command in turnallowing it to get more work done per unit of timeand potentially negating much of the effect of the time lag between transmission and receipt of commands between the rover and earth this string of commands is called macro macros are also useful when running automated tests where you want to mimic user interaction with the systemor when you want to automate certain tasks that you do repeatedly you could create command for each step in the process and then string them up before letting some invoker handle the execution the decoupling allows you to swap out direct human intervention via the keyboard for generated computer input once we begin stringing commands togetherwe can also look at undoing the commands that were executed this is another area where the command pattern is particularly useful by pushing an undo command onto stack for every command that gets invokedwe get multi-level undo for freemuch like you see in everything from modern word processors to video-editing software to illustrate how you could go about using the command pattern to build multilevel undo stackwe are going to build very simple calculator that can do additionsubtractionmultiplicationand division for the sake of keeping the example simplewe will not concern ourselves with the case where we have multiplication by zero
8,084
command pattern class addcommand(object)def __init__(selfreceivervalue)self receiver receiver self value value def execute(self)self receiver add(self valuedef undo(self)self receiver subtract(self valueclass subtractcommand(object)def __init__(selfreceivervalue)self receiver receiver self value value def execute(self)self receiver subtract(self valuedef undo(self)self receiver add(self valueclass multiplycommand(object)def __init__(selfreceivervalue)self receiver receiver self value value def execute(self)self receiver multiply(self valuedef undo(self)self receiver divide(self valueclass dividecommand(object)def __init__(selfreceivervalue)self receiver receiver self value value def execute(self)self receiver divide(self value
8,085
command pattern def undo(self)self receiver multiply(self valueclass calculationinvoker(object)def __init__(self)self commands [self undo_stack [def add_new_command(selfcommand)self commands append(commanddef run(self)for command in self commandscommand execute(self undo_stack append(commanddef undo(self)undo_command self undo_stack pop(undo_command undo(class accumulator(object)def __init__(selfvalue)self _value value def add(selfvalue)self _value +value def subtract(selfvalue)self _value -value def multiply(selfvalue)self _value *value def divide(selfvalue)self _value /value def __str__(self)return "current value{}format(self _value
8,086
command pattern if __name__ ="__main__"acc accumulator( invoker calculationinvoker(invoker add_new_command(addcommand(acc )invoker add_new_command(subtractcommand(acc )invoker add_new_command(multiplycommand(acc )invoker add_new_command(dividecommand(acc )invoker run(print(accinvoker undo(invoker undo(invoker undo(invoker undo(print(accjust note that the __str()__ method is used when python casts the accumulator object to string when printing it as we have seen couple of times nowthe duck typing in python allows us to skip defining an overarching base class to inherit from as long as our commands have execute(and undo(methods and take receiver and value as parameters on constructionwe can use any command we feel like in the preceding codewe push every command that gets executed by the invoker onto stack thenwhen we want to undo commandthe last command is popped from the stack and the undo(method of that command is executed in the case of the calculatorthe inverse calculation is executed to return the value of the accumulator back to what it would have been before the command was executed all implementations of the command class in the command pattern will have method such as execute(that is called by the invoker to execute the command the instance of the command class keeps reference to the receiverthe name of the method to be executedand the values to be used as parameters in the execution the receiver is the only object that knows how to execute the method kept in the commandand it manages its own internal state independent of the other objects in the system the client has no knowledge of the implementation details of the commandand neither do the
8,087
command pattern command or the invoker to be clearthe command object does not execute anythingit is just container by implementing this patternwe have added layer of abstraction between the action to be executed and the object that invokes that action the added abstraction leads to better interaction between different objects in the systemand looser coupling between themmaking the system easier to maintain and update the heart of this design pattern is the translation of method calls into data that can be saved in variablepassed to method or function as parameterand returned from function as result the result of applying this pattern is that functions or methods become first-class citizens when functions are first class citizens variables can point to functionsfunctions can be passed as parameter to other functionsand they can be returned as the result from executing function what is interesting about the command patternspecifically this ability to turn behavior into first-class citizenis that we could use this pattern to implement functional programming style with lazy evaluationmeaning that functions could be passed to other functions and could be returned by functions all functions get passed all that is needed for executionwith no global stateand functions are only executed when an actual result needs to be returned this is fairly shallow description of functional programmingbut the implications are deep the interesting twist in our tale is that in python everything is functionand as such we could also do away with the class that encapsulates the function call and just pass the function with the relevant parameters to the invoker def text_writer(string string )print("writing {{}format(string string )class invoker(object)def __init__(self)self commands [def add_command(selfcommand)self commands append(commanddef run(self)for command in self commandscommand["function"](*command["params"]
8,088
command pattern if __name__ ="__main__"invoker invoker(invoker add_command("function"text_writer"params"("command ""string "}invoker add_command("function"text_writer"params"("command ""string "}invoker run(for simple case like thisyou could just define lambda functionand you would not even have to write the function definition class invoker(object)def __init__(self)self commands [def add_command(selfcommand)self commands append(commanddef run(self)for command in self commandscommand["function"](*command["params"]if __name__ ="__main__" lambda string string print("writing {{}format (string string )invoker invoker(invoker add_command("function" "params"("command ""string "}invoker add_command("function"
8,089
command pattern "params"("command ""string "}invoker run(once the function you want to execute gets more complicatedyou have two options other than the method we used in the previous program you could just wrap the command' execute(function in lambdaletting you avoid creating class even though it is nifty trickyour code will probably be more clear if you just create class for the complex casewhich is the second option soa good rule of thumb is that when you need to create command for anything more complex than piece of code you can wrap in single-line lambda functioncreate class for it parting shots whether you are building self-driving car or sending messages to outer spacedecoupling the request for execution from the actual execution allows you to not only buffer actions that need to be executedbut also exchange the mode of input it is important that the command pattern isolates the invoker from the receiver it also separates the time the execution is set up from the time it is processed exercises use the command pattern to create command-line wordreplacement script that can replace every instance of given word in given text file with some other word thenadd command to undo the last replace action
8,090
interpreter pattern silvia broomewhat do you do when you can' sleeptobin kelleri stay awake --the interpreter sometimes it makes sense to not use python to describe problem or the solution to such problem when we need language geared toward specific problem domainwe turn to something called domain-specific language omain-specific languages some languageslike pythonwere created to tackle any type of problem python belongs to whole family of languagescalled general-purpose languagesdesigned to be used to solve any problem on rare occasionsit makes more sense to create language that does only one thingbut that does it extremely well these languageswhich belongto family called domain-specific languages (dsls)are helpful for people who are experts in some specific domain but are not programmers you have probably already encountered dsls in your programming career if you ever tinkered on websiteyou know csswhich is dsl for defining how html should be rendered in browser style css body color# ff (cwessel badenhorst badenhorstpractical python design patterns
8,091
interpreter pattern this little bit of css code tells browser to render all the text inside the body tag of the web page that uses this css file in green the code needed by the browser to do this is lot more complex than this simple snippet of codeyet css is simple enough for most people to pick up in couple of hours html itself is dsl that is interpreted by the browser and displayed as formatted document with fairly intricate layout alternativelyyou may have used aloe in behavior-driven developmentwhere you define acceptance criteria for project in human-readable sentences install the aloe framework using pip pip install aloe nowwe can write some tests zero feature featurecompute factorial in order to play with aloe as beginners we'll implement factorial scenariofactorial of given have the number when compute its factorial then see the number nextyou map these steps to some python code so the aloe framework can understand the behavior described steps py from aloe import @step( ' have the number (\ +)'def have_the_number(stepnumber)world number int(number@step(' compute its factorial'def compute_its_factorial(step)world number factorial(world number
8,092
interpreter pattern @step( ' see the number (\ +)'def check_number(stepexpected)expected int(expectedassert world number =expected"got %dworld number def factorial(number)return - this code lets you define the outcome of the program in terms that non-technical person can understand and then maps those terms to actual codewhich makes sure that they execute as described in the features file the description in the feature file is the dsland the python code in the steps py file is used to change the words and phrases in the dsl into something computer can understand when you decide to create dsl (practice domain engineering)you are enabling clear communication between domain experts and developers not only will the experts be able to express themselves more clearlybut the developers will understand what they requireand so will the computer what you will generally find is that domain expert will describe problemor the solution to problemfrom their domain to developerwho will then immediately write down the description in the domain-specific language domain experts can understand this description of the problem or solution as presented by the developer and will be able to suggest changes or expansions to the description descriptions can thus be turned into functioning solutions during the course of meetingor over couple of days at mostgreatly increasing the productivity of everyone involved let' make this practical you have been contracted to create system restaurants can use to define their specials these specials sometimes have simple rules like buy one get one freebut other times they are lot more complexlike if you buy three pizzas on tuesdaythe cheapest one is free the challenge is that these rules change oftenand as such redeploying the code for every change just does not make sense if you did not care about being forced to change the code every week when your customer decides to change the rules for specialsthe potential magnitude of the if statement this would result in should be enough to scare you off since we have been talking about dslsyou might suspect that creating dsl for the restaurant is the solution any changes or additions to the criteria for special could then be stored independent of the main application and only be interpreted when called upon
8,093
interpreter pattern in very informative talkneil greentechnical lead at icesuggested the following process for developing dsl understand your domain model your domain implement your domain if we were to follow neil' guidancewe would go talk to the restaurant owner we would try to learn how he or she expresses the rules for specialsand then try to capture these rules in language that makes sense to us as well as to the owner we would then draw some sort of diagram based on our conversation if the owner agrees that we captured the essence of what he or she was sayingwe get to write some code to implement our model dsls come in two flavorsinternal and external external dsls have code written in an external file or as string this string or file is then read and parsed by the application before it gets used css is an example of an external dslwhere the browser is tasked with readingparsingand interpreting the textual data that represents how html elements should be displayed internal dslson the other handuse features of the language--pythonin this case--to enable people to write code that resembles the domain syntaxan example would be how numpy uses python to allow mathematicians to describe linear algebra problems the interpreter pattern specifically caters to internal dsls the idea is to create syntax that is significantly less comprehensive than generalpurpose languageyet significantly more expressivespecifically as it relates to the domain in question have look at the following codewhich defines rules for specials run by our imaginary restaurant and is written as conditionals in python pizzas [item for tab items if item type ="pizza"if len(pizzas and day_of_week = cheapest_pizza_price min([pizza price for pizza in pizzas]tab add_discount(cheapest_pizza_pricedrinks [item for tab items if item type ="drink"if hour_now for item in tab itemsif item type ="drink"item price item price
8,094
interpreter pattern if tab customer is_member()for item in tab itemsitem price item price nowlook at the stark contrast between the previous code snippet and the definition of the same rules in simple dsl for defining specials if tab contains pizzas on wednesdays cheapest one is free every day from : to : drinks are less all items are less for members we will not yet look at the interpretationwhich will come little later what want you to notice is how much more clearly the dsl communicates how the rules of the specials will be applied it is written in way that will make sense to business owner and will allow them to either affirm that it does indeed fit their intent or that mistake was made and corrections will be needed ambiguity is reducedand adding new rules or specials becomes more simple-- win on both counts advantages of dsls the level of understanding and communication with regards to the domain for which the dsl is created is greatly elevated domain experts can reason about the expression of both the problem and the solution in the dsl without their having software engineering background the development of business information systems can thus move from software developers to the domain experts this results in richermore accurate systems expressed in terms the experts being aided by the system can understand disadvantages of dsls before you head out and begin creating dsls for every problem domain you can dream ofremember that there is cost involved in learning dsleven if it makes sense for the domain experts someone new may understand what your dsl is expressingbut they will still need to learn the language implementation in order to be able to work with it the deeper and richer your dslthe more knowledge the domain expert needs to operate the languagewhich might have an impact on the number of people who will be
8,095
interpreter pattern able to use and maintain the system keep in mind that the use of dsl should aid the businessnot hamper itor it will discard the language in the long runif it ever adopts it in the first place we have considered the pros and cons of having dsl and decide to move forward with one for specifying rules for the restaurant specials on macro levelyou want to accomplish two tasks firstyou want to define the language specificallyyou want to define the semantics (meaningand syntax (structureof the language nextyou want to write code that will be able to take the language as input and translate it into form that machine can understand and action based on your conversations with customersextract the things that are involved in the process as well as the actions taken by every entity involved after thisisolate common words or phrases that have specific meaning in the domain under consideration use these three elements to construct grammarwhich you will discuss with the domain experts before implementing it before we look at an example of this process in the context of the restaurant specialsi want you start thinking of yourself as tool maker whenever you encounter frustration or problemyou should begin thinking of how you would go about solving this problem and what tools you would code to make the process ten times easier or faster this is the mindset that sets the best software developers and engineers apart from the rest of the field in our example casewe started by having series of conversations with the restaurant owner (the domain expertand identified the following rules for specialsmembers always get off their total tab during happy hourwhich happens from : to : weekdaysall drinks are less mondays are buy one get one free burger nights thursday are 'eat all you canribs sunday nights after : buy three pizzas and get the cheapest one free when you buy you get the two cheapest ones free and so on for every three additional pizzas thenwe identified the things that were mentionedmembers tabs happy hour
8,096
interpreter pattern drinks weekdays mondays burgers thursday ribs sunday pizzas we also identified the actions that could take placeget discount get discount get one free eat all you can finallywe recognized the key ideas as they relate to specials in the restaurantif customer is of certain type they always get fixed off their total tab at certain times all items of specific type gets discounted with fixed percentage at certain times you get second item of certain type free if you were to buy one item of that type generalizing the elements in the key ideas results in the following rules for specialsif certain conditions are met certain items get discount one way to formally express grammar is by writing it in extended backus-naur form (ebnf for more information on ebnf seecmsc /tutorial/ebnf htmlour restaurant example in enbf looks like thisrule"if "conditionsthen "item_typeget "discount conditionscondition conditions and conditions conditions or conditions conditiontime_condition item_condition customer_condition discountnumber"discount"cheapest "numberitem_type free
8,097
interpreter pattern time_condition"today is "day_of_week "time is between "timeand "time "today is week day"today not week dayday_of_week"monday"tuesday"wednesday"thursday"friday"saturday"sundaytimehours":"minutes hourshour_tenshour_ones hour_tens" " hour_onesdigit minutesminute_tensminute_ones minute_tens" " " " " " minute_onesdigit item_condition"item is "item_type "there are "numberof "item_type item_type"pizza"burger"drink"chipsnumber{digitdigit" " " " " " " " " " customer_condition"customer is "customer_type customer_type"member"non-memberyou have set of terminal symbols that cannot be substituted with any patternas well as set of non-terminal production rules that can be used to replace non-terminal ( place holder symbolwith sequence of terminals or with some recipe of other non-terminal patterns different ways in which non-terminal can be substituted are separated by the pipe character "|when you are creating an external dsla package such as pyparsing can be used to translate strings written in grammar like the one just seen to data type that can be handled by python code you have now seen an example of how you can move through the process of domain modeling by understanding the domain via conversations with domain expertsidentifying key elements of the domaincodifying this understanding in some sort of domain model that can be verified by domain expertsand finally implementing the dsl as final product of the process from this point onwe will be dealing with an internal dsl if we were to implement the special rules as an internal dslwe would need to basically create one class per symbol
8,098
interpreter pattern we begin by creating just the stubs based on the grammar we defined earlierclass tab(object)pass class item(object)pass class customer(object)pass class discount(object)pass class rule(object)pass class customertype(object)pass class itemtype(object)pass class conditions(object)pass class condition(object)pass class timecondition(object)pass class dayofweek(object)pass class time(object)pass class hours(object)pass class hourtens(object)pass
8,099
interpreter pattern class hourones(object)pass class minutes(object)pass class minutetens(object)pass class minuteones(object)pass class itemcondition(object)pass class number(object)pass class digit(object)pass class customercondition(object)pass not all of these classes will be needed in the final designand as such you should pay attention to the yagni principlebasicallythe idea is that you should not build things you are not going to need in this casei have written them all out so you can see that we took every single thing mentioned in the process of defining the grammar and created class for each before we reduce the classes and create the final internal dslwe are going to touch on the composite patternwhich will be useful when we start building our interpreter composite pattern when you have container with elements that could themselves be containersyou have good case for using the composite pattern look at the ebnf version of the grammar we are developing for the restaurantan item can be combo that contains items