Python Design Patterns – Proxy

Python Design Patterns – Proxy ”; Previous Next The proxy design pattern includes a new object, which is called “Proxy” in place of an existing object which is called the “Real Subject”. The proxy object created of the real subject must be on the same interface in such a way that the client should not get any idea that proxy is used in place of the real object. Requests generated by the client to the proxy are passed through the real subject. The UML representation of proxy pattern is as follows − How to implement the proxy pattern? Let us now see how to implement the proxy pattern. class Image: def __init__( self, filename ): self._filename = filename def load_image_from_disk( self ): print(“loading ” + self._filename ) def display_image( self ): print(“display ” + self._filename) class Proxy: def __init__( self, subject ): self._subject = subject self._proxystate = None class ProxyImage( Proxy ): def display_image( self ): if self._proxystate == None: self._subject.load_image_from_disk() self._proxystate = 1 print(“display ” + self._subject._filename ) proxy_image1 = ProxyImage ( Image(“HiRes_10Mb_Photo1”) ) proxy_image2 = ProxyImage ( Image(“HiRes_10Mb_Photo2″) ) proxy_image1.display_image() # loading necessary proxy_image1.display_image() # loading unnecessary proxy_image2.display_image() # loading necessary proxy_image2.display_image() # loading unnecessary proxy_image1.display_image() # loading unnecessary Output The above program generates the following output − The proxy pattern design helps in replicating the images that we created. The display_image() function helps to check if the values are getting printed in the command prompt. Print Page Previous Next Advertisements ”;

Python Design Patterns – State

Python Design Patterns – State ”; Previous Next It provides a module for state machines, which are implemented using subclasses, derived from a specified state machine class. The methods are state independent and cause transitions declared using decorators. How to implement the state pattern? The basic implementation of state pattern is shown below − class ComputerState(object): name = “state” allowed = [] def switch(self, state): “”” Switch to new state “”” if state.name in self.allowed: print ”Current:”,self,” => switched to new state”,state.name self.__class__ = state else: print ”Current:”,self,” => switching to”,state.name,”not possible.” def __str__(self): return self.name class Off(ComputerState): name = “off” allowed = [”on”] class On(ComputerState): “”” State of being powered on and working “”” name = “on” allowed = [”off”,”suspend”,”hibernate”] class Suspend(ComputerState): “”” State of being in suspended mode after switched on “”” name = “suspend” allowed = [”on”] class Hibernate(ComputerState): “”” State of being in hibernation after powered on “”” name = “hibernate” allowed = [”on”] class Computer(object): “”” A class representing a computer “”” def __init__(self, model=”HP”): self.model = model # State of the computer – default is off. self.state = Off() def change(self, state): “”” Change state “”” self.state.switch(state) if __name__ == “__main__”: comp = Computer() comp.change(On) comp.change(Off) comp.change(On) comp.change(Suspend) comp.change(Hibernate) comp.change(On) comp.change(Off) Output The above program generates the following output − Print Page Previous Next Advertisements ”;

Python Design Patterns – Home

Python Design Patterns Tutorial PDF Version Quick Guide Resources Job Search Discussion This tutorial explains the various types of design patterns and their implementation in Python scripting language. This tutorial will take you through a roller coaster ride with different approaches and examples using Python concepts. Audience This tutorial is aimed to benefit both basic and intermediate levels of programmers and developers. Prerequisites Before you proceed with this tutorial, it is assumed that the user is already aware about basic python programming concepts. Print Page Previous Next Advertisements ”;

Discussions

Discuss Python Design Patterns ”; Previous Next This tutorial explains the various types of design patterns and their implementation in Python scripting language. This tutorial will take you through a roller coaster ride with different approaches and examples using Python concepts. Print Page Previous Next Advertisements ”;

Python Design Patterns – Flyweight

Python Design Patterns – Flyweight ”; Previous Next The flyweight patterb comes under the structural design patterns category. It provides a way to decrease object count. It includes various features that help in improving application structure. The most important feature of the flyweight objects is immutable. This means that they cannot be modified once constructed. The pattern uses a HashMap to store reference objects. How to implement the flyweight pattern? The following program helps in implementing the flyweight pattern − class ComplexGenetics(object): def __init__(self): pass def genes(self, gene_code): return “ComplexPatter[%s]TooHugeinSize” % (gene_code) class Families(object): family = {} def __new__(cls, name, family_id): try: id = cls.family[family_id] except KeyError: id = object.__new__(cls) cls.family[family_id] = id return id def set_genetic_info(self, genetic_info): cg = ComplexGenetics() self.genetic_info = cg.genes(genetic_info) def get_genetic_info(self): return (self.genetic_info) def test(): data = ((”a”, 1, ”ATAG”), (”a”, 2, ”AAGT”), (”b”, 1, ”ATAG”)) family_objects = [] for i in data: obj = Families(i[0], i[1]) obj.set_genetic_info(i[2]) family_objects.append(obj) for i in family_objects: print “id = ” + str(id(i)) print i.get_genetic_info() print “similar id”s says that they are same objects ” if __name__ == ”__main__”: test() Output The above program generates the following output − Print Page Previous Next Advertisements ”;

Python Design Patterns – Anti

Python Design Patterns – Anti ”; Previous Next Anti-patterns follow a strategy in opposition to predefined design patterns. The strategy includes common approaches to common problems, which can be formalized and can be generally considered as a good development practice. Usually, anti-patterns are opposite and undesirable. Anti- patterns are certain patterns used in software development, which are considered as bad programming practices. Important features of anti-patterns Let us now see a few important features of anti-patterns. Correctness These patterns literally break your code and make you do wrong things. Following is a simple illustration of this − class Rectangle(object): def __init__(self, width, height): self._width = width self._height = height r = Rectangle(5, 6) # direct access of protected member print(“Width: {:d}”.format(r._width)) Maintainability A program is said to be maintainable if it is easy to understand and modify as per the requirement. Importing module can be considered as an example of maintainability. import math x = math.ceil(y) # or import multiprocessing as mp pool = mp.pool(8) Example of anti-pattern Following example helps in the demonstration of anti-patterns − #Bad def filter_for_foo(l): r = [e for e in l if e.find(“foo”) != -1] if not check_some_critical_condition(r): return None return r res = filter_for_foo([“bar”,”foo”,”faz”]) if res is not None: #continue processing pass #Good def filter_for_foo(l): r = [e for e in l if e.find(“foo”) != -1] if not check_some_critical_condition(r): raise SomeException(“critical condition unmet!”) return r try: res = filter_for_foo([“bar”,”foo”,”faz”]) #continue processing except SomeException: i = 0 while i < 10: do_something() #we forget to increment i Explanation The example includes the demonstration of good and bad standards for creating a function in Python. Print Page Previous Next Advertisements ”;

Lists Data Structure

Lists Data Structure ”; Previous Next The Lists data structure is a versatile datatype in Python, which can be written as a list of comma separated values between square brackets. Syntax Here is the basic syntax for the structure − List_name = [ elements ]; If you observe, the syntax is declared like arrays with the only difference that lists can include elements with different data types. The arrays include elements of the same data type. A list can contain a combination of strings, integers and objects. Lists can be used for the implementation of stacks and queues. Lists are mutable. These can be changed as and when needed. How to implement lists? The following program shows the implementations of lists − my_list = [”p”,”r”,”o”,”b”,”e”] # Output: p print(my_list[0]) # Output: o print(my_list[2]) # Output: e print(my_list[4]) # Error! Only integer can be used for indexing # my_list[4.0] # Nested List n_list = [“Happy”, [2,0,1,5]] # Nested indexing # Output: a print(n_list[0][1]) # Output: 5 print(n_list[1][3]) Output The above program generates the following output − The built-in functions of Python lists are as follows − Append()− It adds element to the end of list. Extend()− It adds elements of the list to another list. Insert()− It inserts an item to the defined index. Remove()− It deletes the element from the specified list. Reverse()− It reverses the elements in list. sort() − It helps to sort elements in chronological order. Print Page Previous Next Advertisements ”;

Quick Guide

Python Design Patterns – Quick Guide ”; Previous Next Python Design Patterns – Introduction Design patterns are used to represent the pattern used by developers to create software or web application. These patterns are selected based on the requirement analysis. The patterns describe the solution to the problem, when and where to apply the solution and the consequences of the implementation. Structure of a design pattern The documentation of design pattern is maintained in a way that focuses more on the technology that is used and in what ways. The following diagram explains the basic structure of design pattern documentation. Pattern Name It describes the pattern in short and effective manner. Intent/Motive It describes what the pattern does. Applicability It describes the list of situations where pattern is applicable. Participants and consequences Participants include classes and objects that participate in the design pattern with a list of consequences that exist with the pattern. Why Python? Python is an open source scripting language. It has libraries that support a variety of design patterns. The syntax of python is easy to understand and uses English keywords. Python provides support for the list of design patterns that are mentioned below. These design patterns will be used throughout this tutorial − Model View Controller Pattern Singleton pattern Factory pattern Builder Pattern Prototype Pattern Facade Pattern Command Pattern Adapter Pattern Prototype Pattern Decorator Pattern Proxy Pattern Chain of Responsibility Pattern Observer Pattern State Pattern Strategy Pattern Template Pattern Flyweight Pattern Abstract Factory Pattern Object Oriented Pattern Benefits of using design pattern Following are the different benefits of design pattern − Patterns provide developer a selection of tried and tested solutions for the specified problems. All design patterns are language neutral. Patterns help to achieve communication and maintain well documentation. It includes a record of accomplishment to reduce any technical risk to the project. Design patterns are highly flexible to use and easy to understand. Python Design Patterns – Gist Python is an open source scripting language, which is high-level, interpreted, interactive and object-oriented. It is designed to be highly readable. The syntax of Python language is easy to understand and uses English keywords frequently. Features of Python Language In this section, we will learn about the different features of Python language. Interpreted Python is processed at runtime using the interpreter. There is no need to compile program before execution. It is similar to PERL and PHP. Object-Oriented Python follows object-oriented style and design patterns. It includes class definition with various features like encapsulation, polymorphism and many more. Portable Python code written in Windows operating system and can be used in Mac operating system. The code can be reused and portable as per the requirements. Easy to code Python syntax is easy to understand and code. Any developer can understand the syntax of Python within few hours. Python can be described as “programmer-friendly” Extensible If needed, a user can write some of Python code in C language as well. It is also possible to put python code in source code in different languages like C++. This makes Python an extensible language. Important Points Consider the following important points related to Python programming language − It includes functional and structured programming methods as well as object-oriented programming methods. It can be used as scripting language or as a programming language. It includes automatic garbage collection. It includes high-level dynamic data types and supports various dynamic type checking. Python includes a feature of integration with C, C++ and languages like Java. How to download python language in your system? To download Python language in your system, follow this link − https://www.python.org/downloads/ It includes packages for various operating systems like Windows, MacOS and Linux distributions. The Important Tools in Python In this section, we will learn in brief about a few important tools in Python. Python Strings The basic declaration of strings is as follows − str = ”Hello World!” Python Lists The lists of python can be declared as compound data types separated by commas and enclosed within square brackets ([]). list = [ ”abcd”, 786 , 2.23, ”john”, 70.2 ] tinylist = [123, ”john”] Python Tuples A tuple is dynamic data type of Python, which consists of number of values separated by commas. Tuples are enclosed with parentheses. tinytuple = (123, ”john”) Python Dictionary Python dictionary is a type of hash table. A dictionary key can be almost any data type of Python. The data types are usually numbers or strings. tinydict = {”name”: ”omkar”,”code”:6734, ”dept”: ”sales”} What constitutes a design pattern in Python? Python helps in constituting a design pattern using the following parameters − Pattern Name Intent Aliases Motivation Problem Solution Structure Participants Constraints Sample Code Model View Controller Pattern Model View Controller is the most commonly used design pattern. Developers find it easy to implement this design pattern. Following is a basic architecture of the Model View Controller − Let us now see how the structure works. Model It consists of pure application logic, which interacts with the database. It includes all the information to represent data to the end user. View View represents the HTML files, which interact with the end user. It represents the model’s data to user. Controller It acts as an intermediary between view and model. It listens to the events triggered by view and queries model for the same. Python code Let us consider a basic object called “Person” and create an MVC design pattern. Model.py import json class Person(object): def __init__(self, first_name = None, last_name = None): self.first_name = first_name self.last_name = last_name #returns Person name, ex: John Doe def name(self): return (“%s %s” % (self.first_name,self.last_name)) @classmethod #returns all people inside db.txt as list of Person objects def getAll(self): database = open(”db.txt”, ”r”) result = [] json_list = json.loads(database.read()) for item in json_list: item = json.loads(item) person = Person(item[”first_name”], item[”last_name”]) result.append(person) return result It calls for a method, which fetches all the records of the Person table in database. The records are presented in

Chain of Responsibility Pattern

Chain of Responsibility ”; Previous Next The chain of responsibility pattern is used to achieve loose coupling in software where a specified request from the client is passed through a chain of objects included in it. It helps in building a chain of objects. The request enters from one end and moves from one object to another. This pattern allows an object to send a command without knowing which object will handle the request. How to implement the chain of responsibility pattern? We will now see how to implement the chain of responsibility pattern. class ReportFormat(object): PDF = 0 TEXT = 1 class Report(object): def __init__(self, format_): self.title = ”Monthly report” self.text = [”Things are going”, ”really, really well.”] self.format_ = format_ class Handler(object): def __init__(self): self.nextHandler = None def handle(self, request): self.nextHandler.handle(request) class PDFHandler(Handler): def handle(self, request): if request.format_ == ReportFormat.PDF: self.output_report(request.title, request.text) else: super(PDFHandler, self).handle(request) def output_report(self, title, text): print ”<html>” print ” <head>” print ” <title>%s</title>” % title print ” </head>” print ” <body>” for line in text: print ” <p>%s” % line print ” </body>” print ”</html>” class TextHandler(Handler): def handle(self, request): if request.format_ == ReportFormat.TEXT: self.output_report(request.title, request.text) else: super(TextHandler, self).handle(request) def output_report(self, title, text): print 5*”*” + title + 5*”*” for line in text: print line class ErrorHandler(Handler): def handle(self, request): print “Invalid request” if __name__ == ”__main__”: report = Report(ReportFormat.TEXT) pdf_handler = PDFHandler() text_handler = TextHandler() pdf_handler.nextHandler = text_handler text_handler.nextHandler = ErrorHandler() pdf_handler.handle(report) Output The above program generates the following output − Explanation The above code creates a report for monthly tasks where it sends commands through each function. It takes two handlers – for PDF and for text. It prints the output once the required object executes each function. Print Page Previous Next Advertisements ”;

Python Design Patterns – Sets

Python Design Patterns – Sets ”; Previous Next A set can be defined as unordered collection that is iterable, mutable and there is no inclusion of duplicate elements in it. In Python, set class is a notation of mathematical set. The main advantage of using a set is that it includes highly optimized method for checking specific element. Python includes a separate category called frozen sets. These sets are immutable objects that only support methods and operators that produce a required result. How to implement sets? The following program helps in the implementation of sets − # Set in Python # Creating two sets set1 = set() set2 = set() # Adding elements to set1 for i in range(1, 6): set1.add(i) # Adding elements to set2 for i in range(3, 8): set2.add(i) print(“Set1 = “, set1) print(“Set2 = “, set2) print(“n”) # Union of set1 and set2 set3 = set1 | set2# set1.union(set2) print(“Union of Set1 & Set2: Set3 = “, set3) # Intersection of set1 and set2 set4 = set1 & set2# set1.intersection(set2) print(“Intersection of Set1 & Set2: Set4 = “, set4) print(“n”) # Checking relation between set3 and set4 if set3 > set4: # set3.issuperset(set4) print(“Set3 is superset of Set4”) elif set3 < set4: # set3.issubset(set4) print(“Set3 is subset of Set4”) else : # set3 == set4 print(“Set3 is same as Set4”) # displaying relation between set4 and set3 if set4 < set3: # set4.issubset(set3) print(“Set4 is subset of Set3”) print(“n”) # difference between set3 and set4 set5 = set3 – set4 print(“Elements in Set3 and not in Set4: Set5 = “, set5) print(“n”) # checkv if set4 and set5 are disjoint sets if set4.isdisjoint(set5): print(“Set4 and Set5 have nothing in commonn”) # Removing all the values of set5 set5.clear() print(“After applying clear on sets Set5: “) print(“Set5 = “, set5) Output The above program generates the following output − The frozen set can be demonstrated using the following program − normal_set = set([“a”, “b”,”c”]) # Adding an element to normal set is fine normal_set.add(“d”) print(“Normal Set”) print(normal_set) # A frozen set frozen_set = frozenset([“e”, “f”, “g”]) print(“Frozen Set”) print(frozen_set) Output The above program generates the following output − Print Page Previous Next Advertisements ”;