Concurrency in Python ”; Previous Next Concurrency is often misunderstood as parallelism. Concurrency implies scheduling independent code to be executed in a systematic manner. This chapter focuses on the execution of concurrency for an operating system using Python. The following program helps in the execution of concurrency for an operating system − import os import time import threading import multiprocessing NUM_WORKERS = 4 def only_sleep(): print(“PID: %s, Process Name: %s, Thread Name: %s” % ( os.getpid(), multiprocessing.current_process().name, threading.current_thread().name) ) time.sleep(1) def crunch_numbers(): print(“PID: %s, Process Name: %s, Thread Name: %s” % ( os.getpid(), multiprocessing.current_process().name, threading.current_thread().name) ) x = 0 while x < 10000000: x += 1 for _ in range(NUM_WORKERS): only_sleep() end_time = time.time() print(“Serial time=”, end_time – start_time) # Run tasks using threads start_time = time.time() threads = [threading.Thread(target=only_sleep) for _ in range(NUM_WORKERS)] [thread.start() for thread in threads] [thread.join() for thread in threads] end_time = time.time() print(“Threads time=”, end_time – start_time) # Run tasks using processes start_time = time.time() processes = [multiprocessing.Process(target=only_sleep()) for _ in range(NUM_WORKERS)] [process.start() for process in processes] [process.join() for process in processes] end_time = time.time() print(“Parallel time=”, end_time – start_time) Output The above program generates the following output − Explanation “multiprocessing” is a package similar to the threading module. This package supports local and remote concurrency. Due to this module, programmers get the advantage to use multiple processes on the given system. Print Page Previous Next Advertisements ”;
Category: python Design Patterns
Python Design Patterns – Useful Resources ”; Previous Next The following resources contain additional information on Python Design Patterns. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Design Patterns Online Training 32 Lectures 4 hours Tutorialspoint More Detail Learn Creational Design Patterns in Java 26 Lectures 2 hours Samarth Narula More Detail Candlestick Chart Patterns Course For Stock Trading 36 Lectures 1.5 hours Jason Gandy More Detail Candlestick Patterns & Analysis A-Z Masterclass 19 Lectures 1 hours Travis Rose More Detail C# Design Patterns 24 Lectures 4.5 hours Maruti Makwana More Detail Test Driven Object Oriented Design – SOLID, Patterns & LLD 48 Lectures 6.5 hours Akshay Khanna More Detail Print Page Previous Next Advertisements ”;
Dictionaries
Python Design Patterns – Dictionaries ”; Previous Next Dictionaries are the data structures, which include a key value combination. These are widely used in place of JSON – JavaScript Object Notation. Dictionaries are used for API (Application Programming Interface) programming. A dictionary maps a set of objects to another set of objects. Dictionaries are mutable; this means they can be changed as and when needed based on the requirements. How to implement dictionaries in Python? The following program shows the basic implementation of dictionaries in Python starting from its creation to its implementation. # Create a new dictionary d = dict() # or d = {} # Add a key – value pairs to dictionary d[”xyz”] = 123 d[”abc”] = 345 # print the whole dictionary print(d) # print only the keys print(d.keys()) # print only values print(d.values()) # iterate over dictionary for i in d : print(“%s %d” %(i, d[i])) # another method of iteration for index, value in enumerate(d): print (index, value , d[value]) # check if key exist 23. Python Data Structure –print(”xyz” in d) # delete the key-value pair del d[”xyz”] # check again print(“xyz” in d) Output The above program generates the following output − Note −There are drawbacks related to the implementation of dictionaries in Python. Drawback Dictionaries do not support the sequence operation of the sequence data types like strings, tuples and lists. These belong to the built-in mapping type. Print Page Previous Next Advertisements ”;
Python Design Patterns – Queues ”; Previous Next Queue is a collection of objects, which define a simple data structure following the FIFO (Fast In Fast Out) and the LIFO (Last In First Out) procedures. The insert and delete operations are referred as enqueue and dequeue operations. Queues do not allow random access to the objects they contain. How to implement the FIFO procedure? The following program helps in the implementation of FIFO − import Queue q = Queue.Queue() #put items at the end of the queue for x in range(4): q.put(“item-” + str(x)) #remove items from the head of the queue while not q.empty(): print q.get() Output The above program generates the following output − How to implement the LIFO procedure? The following program helps in the implementation of the LIFO procedure − import Queue q = Queue.LifoQueue() #add items at the head of the queue for x in range(4): q.put(“item-” + str(x)) #remove items from the head of the queue while not q.empty(): print q.get() Output The above program generates the following output − What is a Priority Queue? Priority queue is a container data structure that manages a set of records with the ordered keys to provide quick access to the record with smallest or largest key in specified data structure. How to implement a priority queue? The implementation of priority queue is as follows − import Queue class Task(object): def __init__(self, priority, name): self.priority = priority self.name = name def __cmp__(self, other): return cmp(self.priority, other.priority) q = Queue.PriorityQueue() q.put( Task(100, ”a not agent task”) ) q.put( Task(5, ”a highly agent task”) ) q.put( Task(10, ”an important task”) ) while not q.empty(): cur_task = q.get() print ”process task:”, cur_task.name Output The above program generates the following output − Print Page Previous Next Advertisements ”;
Abstract Factory
Python Design Patterns – Abstract Factory ”; Previous Next The abstract factory pattern is also called factory of factories. This design pattern comes under the creational design pattern category. It provides one of the best ways to create an object. It includes an interface, which is responsible for creating objects related to Factory. How to implement the abstract factory pattern? The following program helps in implementing the abstract factory pattern. class Window: __toolkit = “” __purpose = “” def __init__(self, toolkit, purpose): self.__toolkit = toolkit self.__purpose = purpose def getToolkit(self): return self.__toolkit def getType(self): return self.__purpose class GtkToolboxWindow(Window): def __init__(self): Window.__init__(self, “Gtk”, “ToolboxWindow”) class GtkLayersWindow(Window): def __init__(self): Window.__init__(self, “Gtk”, “LayersWindow”) class GtkMainWindow(Window): def __init__(self): Window.__init__(self, “Gtk”, “MainWindow”) class QtToolboxWindow(Window): def __init__(self): Window.__init__(self, “Qt”, “ToolboxWindow”) class QtLayersWindow(Window): def __init__(self): Window.__init__(self, “Qt”, “LayersWindow”) class QtMainWindow(Window): def __init__(self): Window.__init__(self, “Qt”, “MainWindow”) # Abstract factory class class UIFactory: def getToolboxWindow(self): pass def getLayersWindow(self): pass def getMainWindow(self): pass class GtkUIFactory(UIFactory): def getToolboxWindow(self): return GtkToolboxWindow() def getLayersWindow(self): return GtkLayersWindow() def getMainWindow(self): return GtkMainWindow() class QtUIFactory(UIFactory): def getToolboxWindow(self): return QtToolboxWindow() def getLayersWindow(self): return QtLayersWindow() def getMainWindow(self): return QtMainWindow() if __name__ == “__main__”: gnome = True kde = not gnome if gnome: ui = GtkUIFactory() elif kde: ui = QtUIFactory() toolbox = ui.getToolboxWindow() layers = ui.getLayersWindow() main = ui.getMainWindow() print “%s:%s” % (toolbox.getToolkit(), toolbox.getType()) print “%s:%s” % (layers.getToolkit(), layers.getType()) print “%s:%s” % (main.getToolkit(), main.getType()) Output The above program generates the following output − Explanation In the above program, the abstract factory creates objects for each window. It calls for each method, which executes the output as expected. Print Page Previous Next Advertisements ”;
Object Oriented
Python Design Patterns – Object Oriented ”; Previous Next The object oriented pattern is the most commonly used pattern. This pattern can be found in almost every programming language. How to implement the object oriented pattern? Let us now see how to implement the object oriented pattern. class Parrot: # class attribute species = “bird” # instance attribute def __init__(self, name, age): self.name = name self.age = age # instantiate the Parrot class blu = Parrot(“Blu”, 10) woo = Parrot(“Woo”, 15) # access the class attributes print(“Blu is a {}”.format(blu.__class__.species)) print(“Woo is also a {}”.format(woo.__class__.species)) # access the instance attributes print(“{} is {} years old”.format( blu.name, blu.age)) print(“{} is {} years old”.format( woo.name, woo.age)) Output The above program generates the following output Explanation The code includes class attribute and instance attributes, which are printed as per the requirement of the output. There are various features that form part of the object oriented pattern. The features are explained in the next chapter. Print Page Previous Next Advertisements ”;
Strings & Serialization
Strings and Serialization ”; Previous Next String serialization is the process of writing a state of object into a byte stream. In python, the “pickle” library is used for enabling serialization. This module includes a powerful algorithm for serializing and de-serializing a Python object structure. “Pickling” is the process of converting Python object hierarchy into byte stream and “unpickling” is the reverse procedure. The demonstration of the pickle module is as follows − import pickle #Here”s an example dict grades = { ”Alice”: 89, ”Bob”: 72, ”Charles”: 87 } #Use dumps to convert the object to a serialized string serial_grades = pickle.dumps( grades ) print(serial_grades) #Use loads to de-serialize an object received_grades = pickle.loads( serial_grades ) print(received_grades) Output The above program generates the following output − Print Page Previous Next Advertisements ”;
Python Design Patterns – Template ”; Previous Next A template pattern defines a basic algorithm in a base class using abstract operation where subclasses override the concrete behavior. The template pattern keeps the outline of algorithm in a separate method. This method is referred as the template method. Following are the different features of the template pattern − It defines the skeleton of algorithm in an operation It includes subclasses, which redefine certain steps of an algorithm. class MakeMeal: def prepare(self): pass def cook(self): pass def eat(self): pass def go(self): self.prepare() self.cook() self.eat() class MakePizza(MakeMeal): def prepare(self): print “Prepare Pizza” def cook(self): print “Cook Pizza” def eat(self): print “Eat Pizza” class MakeTea(MakeMeal): def prepare(self): print “Prepare Tea” def cook(self): print “Cook Tea” def eat(self): print “Eat Tea” makePizza = MakePizza() makePizza.go() print 25*”+” makeTea = MakeTea() makeTea.go() Output The above program generates the following output − Explanation This code creates a template to prepare meal. Here, each parameter represents the attribute to create a part of meal like tea, pizza, etc. The output represents the visualization of attributes. Print Page Previous Next Advertisements ”;
Object Oriented Concepts Implementation ”; Previous Next In this chapter, we will focus on patterns using object oriented concepts and its implementation in Python. When we design our programs around blocks of statements, which manipulate the data around functions, it is called procedure-oriented programming. In object-oriented programming, there are two main instances called classes and objects. How to implement classes and object variables? The implementation of classes and object variables are as follows − class Robot: population = 0 def __init__(self, name): self.name = name print(“(Initializing {})”.format(self.name)) Robot.population += 1 def die(self): print(“{} is being destroyed!”.format(self.name)) Robot.population -= 1 if Robot.population == 0: print(“{} was the last one.”.format(self.name)) else: print(“There are still {:d} robots working.”.format( Robot.population)) def say_hi(self): print(“Greetings, my masters call me {}.”.format(self.name)) @classmethod def how_many(cls): print(“We have {:d} robots.”.format(cls.population)) droid1 = Robot(“R2-D2”) droid1.say_hi() Robot.how_many() droid2 = Robot(“C-3PO”) droid2.say_hi() Robot.how_many() print(“nRobots can do some work here.n”) print(“Robots have finished their work. So let”s destroy them.”) droid1.die() droid2.die() Robot.how_many() Output The above program generates the following output − Explanation This illustration helps to demonstrate the nature of class and object variables. “population” belongs to the “Robot” class. Hence, it is referred to as a class variable or object. Here, we refer to the population class variable as Robot.population and not as self.population. Print Page Previous Next Advertisements ”;
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 ”;