Bladeren bron

Fixed PEP-8 voilations.

* add python headers.
* Remove extra whitespaces.
Saurabh Kumar 11 jaren geleden
bovenliggende
commit
efe44d6532
23 gewijzigde bestanden met toevoegingen van 151 en 90 verwijderingen
  1. 19 19
      README.md
  2. 3 0
      abstract_factory.py
  3. 4 1
      adapter.py
  4. 3 0
      borg.py
  5. 8 5
      bridge.py
  6. 3 0
      catalog.py
  7. 4 1
      chain.py
  8. 4 1
      command.py
  9. 38 35
      composite.py
  10. 4 1
      decorator.py
  11. 3 0
      facade.py
  12. 5 3
      factory_method.py
  13. 3 0
      flyweight.py
  14. 10 7
      graph_search.py
  15. 3 0
      iterator.py
  16. 3 0
      mediator.py
  17. 4 1
      memento.py
  18. 3 2
      null.py
  19. 4 1
      observer.py
  20. 3 0
      pool.py
  21. 3 0
      prototype.py
  22. 16 13
      proxy.py
  23. 1 0
      publish_subscribe.py

+ 19 - 19
README.md

@@ -1,35 +1,35 @@
 python-patterns
 python-patterns
 ===============
 ===============
 
 
-A collection of design patterns implemented (by other people) in python
+A collection of design patterns implemented (by other people) in python.
 
 
 Current Patterns:
 Current Patterns:
 
 
-* 3-tier		
-* composite		
+* 3-tier
+* composite
 * mvc
 * mvc
-* decorator		
+* decorator
 * null
 * null
-* facade		
+* facade
 * observer
 * observer
-* abstract_factory	
-* factory_method	
+* abstract_factory
+* factory_method
 * pool
 * pool
-* adapter		
-* flyweight		
+* adapter
+* flyweight
 * prototype
 * prototype
-* borg					
+* borg
 * proxy
 * proxy
-* bridge		
-* graph_search		
+* bridge
+* graph_search
 * state
 * state
-* builder		
-* iterator		
+* builder
+* iterator
 * strategy
 * strategy
-* chain		
-* mediator		
+* chain
+* mediator
 * template
 * template
-* command		
-* memento		
+* command
+* memento
 * visitor
 * visitor
-* publish_subscribe
+* publish_subscribe

+ 3 - 0
abstract_factory.py

@@ -1,3 +1,6 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 # http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
 # http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
 
 
 """Implementation of the abstract factory pattern"""
 """Implementation of the abstract factory pattern"""

+ 4 - 1
adapter.py

@@ -1,4 +1,7 @@
-# http://ginstrom.com/scribbles/2008/11/06/generic-adapter-class-in-python/
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""http://ginstrom.com/scribbles/2008/11/06/generic-adapter-class-in-python/"""
 
 
 import os
 import os
 
 

+ 3 - 0
borg.py

@@ -1,3 +1,6 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 class Borg:
 class Borg:
     __shared_state = {}
     __shared_state = {}
 
 

+ 8 - 5
bridge.py

@@ -1,4 +1,7 @@
-# http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Bridge_Pattern#Python
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Bridge_Pattern#Python"""
 
 
 
 
 # ConcreteImplementor 1/2
 # ConcreteImplementor 1/2
@@ -20,11 +23,11 @@ class CircleShape(object):
         self._y = y
         self._y = y
         self._radius = radius
         self._radius = radius
         self._drawing_api = drawing_api
         self._drawing_api = drawing_api
- 
+
     # low-level i.e. Implementation specific
     # low-level i.e. Implementation specific
     def draw(self):
     def draw(self):
         self._drawing_api.draw_circle(self._x, self._y, self._radius)
         self._drawing_api.draw_circle(self._x, self._y, self._radius)
- 
+
     # high-level i.e. Abstraction specific
     # high-level i.e. Abstraction specific
     def scale(self, pct):
     def scale(self, pct):
         self._radius *= pct
         self._radius *= pct
@@ -35,11 +38,11 @@ def main():
         CircleShape(1, 2, 3, DrawingAPI1()),
         CircleShape(1, 2, 3, DrawingAPI1()),
         CircleShape(5, 7, 11, DrawingAPI2())
         CircleShape(5, 7, 11, DrawingAPI2())
     )
     )
- 
+
     for shape in shapes:
     for shape in shapes:
         shape.scale(2.5)
         shape.scale(2.5)
         shape.draw()
         shape.draw()
- 
+
 
 
 if __name__ == '__main__':
 if __name__ == '__main__':
     main()
     main()

+ 3 - 0
catalog.py

@@ -1,3 +1,6 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 """
 """
 A class that uses different static function depending of a parameter passed in init
 A class that uses different static function depending of a parameter passed in init
 Note the use of a single dictionnary instead of multiple conditions
 Note the use of a single dictionnary instead of multiple conditions

+ 4 - 1
chain.py

@@ -1,4 +1,7 @@
-# http://www.testingperspective.com/wiki/doku.php/collaboration/chetan/designpatternsinpython/chain-of-responsibilitypattern
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""http://www.testingperspective.com/wiki/doku.php/collaboration/chetan/designpatternsinpython/chain-of-responsibilitypattern"""
 
 
 
 
 class Handler:
 class Handler:

+ 4 - 1
command.py

@@ -1,3 +1,6 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 import os
 import os
 
 
 
 
@@ -34,4 +37,4 @@ def main():
         cmd.undo()
         cmd.undo()
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    main()
+    main()

+ 38 - 35
composite.py

@@ -1,9 +1,12 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 """
 """
 A class which defines a composite object which can store
 A class which defines a composite object which can store
 hieararchical dictionaries with names.
 hieararchical dictionaries with names.
 
 
 This class is same as a hiearchical dictionary, but it
 This class is same as a hiearchical dictionary, but it
-provides methods to add/access/modify children by name, 
+provides methods to add/access/modify children by name,
 like a Composite.
 like a Composite.
 
 
 Created Anand B Pillai     <abpillai@gmail.com>
 Created Anand B Pillai     <abpillai@gmail.com>
@@ -17,7 +20,7 @@ __version__ = "0.2"
 def normalize(val):
 def normalize(val):
     """ Normalize a string so that it can be used as an attribute
     """ Normalize a string so that it can be used as an attribute
     to a Python object """
     to a Python object """
-    
+
     if val.find('-') != -1:
     if val.find('-') != -1:
         val = val.replace('-', '_')
         val = val.replace('-', '_')
 
 
@@ -65,7 +68,7 @@ class SpecialDict(dict):
             else:
             else:
                 # New attribute
                 # New attribute
                 self[name] = value
                 self[name] = value
-        
+
 
 
 class CompositeDict(SpecialDict):
 class CompositeDict(SpecialDict):
     """ A class which works like a hierarchical dictionary.
     """ A class which works like a hierarchical dictionary.
@@ -106,7 +109,7 @@ class CompositeDict(SpecialDict):
                     attr = getattr(self[self._name], name)
                     attr = getattr(self[self._name], name)
                     if attr:
                     if attr:
                         return attr
                         return attr
-                    
+
                     raise AttributeError('no attribute named %s' % name)
                     raise AttributeError('no attribute named %s' % name)
 
 
     def isRoot(self):
     def isRoot(self):
@@ -114,7 +117,7 @@ class CompositeDict(SpecialDict):
 
 
         # If I don't have a parent, I am root
         # If I don't have a parent, I am root
         return not self._father
         return not self._father
-    
+
     def isLeaf(self):
     def isLeaf(self):
         """ Return whether I am a leaf component or not """
         """ Return whether I am a leaf component or not """
 
 
@@ -128,7 +131,7 @@ class CompositeDict(SpecialDict):
 
 
     def getIndex(self, child):
     def getIndex(self, child):
         """ Return the index of the child ConfigInfo object 'child' """
         """ Return the index of the child ConfigInfo object 'child' """
-        
+
         if child in self._children:
         if child in self._children:
             return self._children.index(child)
             return self._children.index(child)
         else:
         else:
@@ -136,7 +139,7 @@ class CompositeDict(SpecialDict):
 
 
     def getDict(self):
     def getDict(self):
         """ Return the contained dictionary """
         """ Return the contained dictionary """
-        
+
         return self[self._name]
         return self[self._name]
 
 
     def getProperty(self, child, key):
     def getProperty(self, child, key):
@@ -156,25 +159,25 @@ class CompositeDict(SpecialDict):
         childDict = self.getInfoDict(child)
         childDict = self.getInfoDict(child)
         if childDict:
         if childDict:
             childDict[key] = value
             childDict[key] = value
-    
+
     def getChildren(self):
     def getChildren(self):
         """ Return the list of immediate children of this object """
         """ Return the list of immediate children of this object """
-        
+
         return self._children
         return self._children
 
 
     def getAllChildren(self):
     def getAllChildren(self):
         """ Return the list of all children of this object """
         """ Return the list of all children of this object """
-        
+
         l = []
         l = []
         for child in self._children:
         for child in self._children:
             l.append(child)
             l.append(child)
             l.extend(child.getAllChildren())
             l.extend(child.getAllChildren())
-            
+
         return l
         return l
 
 
     def getChild(self, name):
     def getChild(self, name):
         """ Return the immediate child object with the given name """
         """ Return the immediate child object with the given name """
-        
+
         for child in self._children:
         for child in self._children:
             if child.getName() == name:
             if child.getName() == name:
                 return child
                 return child
@@ -185,7 +188,7 @@ class CompositeDict(SpecialDict):
         # Note - this returns the first child of the given name
         # Note - this returns the first child of the given name
         # any other children with similar names down the tree
         # any other children with similar names down the tree
         # is not considered.
         # is not considered.
-        
+
         for child in self.getAllChildren():
         for child in self.getAllChildren():
             if child.getName() == name:
             if child.getName() == name:
                 return child
                 return child
@@ -195,33 +198,33 @@ class CompositeDict(SpecialDict):
 
 
         # Note: this returns a list of all the children of a given
         # Note: this returns a list of all the children of a given
         # name, irrespective of the depth of look-up.
         # name, irrespective of the depth of look-up.
-        
+
         children = []
         children = []
-        
+
         for child in self.getAllChildren():
         for child in self.getAllChildren():
             if child.getName() == name:
             if child.getName() == name:
                 children.append(child)
                 children.append(child)
 
 
         return children
         return children
-            
+
     def getPropertyDict(self):
     def getPropertyDict(self):
         """ Return the property dictionary """
         """ Return the property dictionary """
-        
+
         d = self.getChild('__properties')
         d = self.getChild('__properties')
         if d:
         if d:
             return d.getDict()
             return d.getDict()
         else:
         else:
             return {}
             return {}
-        
+
     def getParent(self):
     def getParent(self):
         """ Return the person who created me """
         """ Return the person who created me """
 
 
         return self._father
         return self._father
-    
+
     def __setChildDict(self, child):
     def __setChildDict(self, child):
         """ Private method to set the dictionary of the child
         """ Private method to set the dictionary of the child
         object 'child' in the internal dictionary """
         object 'child' in the internal dictionary """
-        
+
         d = self[self._name]
         d = self[self._name]
         d[child.getName()] = child.getDict()
         d[child.getName()] = child.getDict()
 
 
@@ -236,25 +239,25 @@ class CompositeDict(SpecialDict):
         # child is orphaned - see addChild and addChild2
         # child is orphaned - see addChild and addChild2
         # methods !
         # methods !
         self._father = father
         self._father = father
-        
+
     def setName(self, name):
     def setName(self, name):
-        """ Set the name of this ConfigInfo object to 'name' """        
+        """ Set the name of this ConfigInfo object to 'name' """
 
 
         self._name = name
         self._name = name
 
 
     def setDict(self, d):
     def setDict(self, d):
         """ Set the contained dictionary """
         """ Set the contained dictionary """
-        
+
         self[self._name] = d.copy()
         self[self._name] = d.copy()
-        
+
     def setAttribute(self, name, value):
     def setAttribute(self, name, value):
         """ Set a name value pair in the contained dictionary """
         """ Set a name value pair in the contained dictionary """
-        
+
         self[self._name][name] = value
         self[self._name][name] = value
 
 
     def getAttribute(self, name):
     def getAttribute(self, name):
         """ Return value of an attribute from the contained dictionary """
         """ Return value of an attribute from the contained dictionary """
-        
+
         return self[self._name][name]
         return self[self._name][name]
 
 
     def addChild(self, name, force=False):
     def addChild(self, name, force=False):
@@ -264,10 +267,10 @@ class CompositeDict(SpecialDict):
 
 
         This function returns the child object, whether
         This function returns the child object, whether
         new or existing """
         new or existing """
-        
+
         if type(name) != str:
         if type(name) != str:
             raise ValueError('Argument should be a string!')
             raise ValueError('Argument should be a string!')
-        
+
         child = self.getChild(name)
         child = self.getChild(name)
         if child:
         if child:
             # print 'Child %s present!' % name
             # print 'Child %s present!' % name
@@ -278,22 +281,22 @@ class CompositeDict(SpecialDict):
                     child = self.__class__(name)
                     child = self.__class__(name)
                     self._children[index] = child
                     self._children[index] = child
                     child.setParent(self)
                     child.setParent(self)
-                    
+
                     self.__setChildDict(child)
                     self.__setChildDict(child)
             return child
             return child
         else:
         else:
             child = self.__class__(name)
             child = self.__class__(name)
             child.setParent(self)
             child.setParent(self)
-            
+
             self._children.append(child)
             self._children.append(child)
             self.__setChildDict(child)
             self.__setChildDict(child)
 
 
             return child
             return child
-        
+
     def addChild2(self, child):
     def addChild2(self, child):
         """ Add the child object 'child'. If it is already present,
         """ Add the child object 'child'. If it is already present,
         it is overwritten by default """
         it is overwritten by default """
-        
+
         currChild = self.getChild(child.getName())
         currChild = self.getChild(child.getName())
         if currChild:
         if currChild:
             index = self.getIndex(currChild)
             index = self.getIndex(currChild)
@@ -303,10 +306,10 @@ class CompositeDict(SpecialDict):
                 # Unset the existing child's parent
                 # Unset the existing child's parent
                 currChild.setParent(None)
                 currChild.setParent(None)
                 del currChild
                 del currChild
-                
+
                 self.__setChildDict(child)
                 self.__setChildDict(child)
         else:
         else:
-            child.setParent(self)            
+            child.setParent(self)
             self._children.append(child)
             self._children.append(child)
             self.__setChildDict(child)
             self.__setChildDict(child)
 
 
@@ -316,7 +319,7 @@ if __name__ == "__main__":
     frame = window.addChild('Frame')
     frame = window.addChild('Frame')
     tfield = frame.addChild('Text Field')
     tfield = frame.addChild('Text Field')
     tfield.setAttribute('size', '20')
     tfield.setAttribute('size', '20')
-    
+
     btn = frame.addChild('Button1')
     btn = frame.addChild('Button1')
     btn.setAttribute('label', 'Submit')
     btn.setAttribute('label', 'Submit')
 
 

+ 4 - 1
decorator.py

@@ -1,4 +1,7 @@
-# http://stackoverflow.com/questions/3118929/implementing-the-decorator-pattern-in-python
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""http://stackoverflow.com/questions/3118929/implementing-the-decorator-pattern-in-python"""
 
 
 
 
 class foo_decorator(object):
 class foo_decorator(object):

+ 3 - 0
facade.py

@@ -1,3 +1,6 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 """http://dpip.testingperspective.com/?p=26"""
 """http://dpip.testingperspective.com/?p=26"""
 
 
 import time
 import time

+ 5 - 3
factory_method.py

@@ -1,4 +1,6 @@
-#encoding=utf-8
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 """http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/"""
 """http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/"""
 
 
 
 
@@ -8,7 +10,7 @@ class GreekGetter:
         self.trans = dict(dog="σκύλος", cat="γάτα")
         self.trans = dict(dog="σκύλος", cat="γάτα")
 
 
     def get(self, msgid):
     def get(self, msgid):
-        """We'll punt if we don't have a translation"""          
+        """We'll punt if we don't have a translation"""
         try:
         try:
             return self.trans[msgid]
             return self.trans[msgid]
         except KeyError:
         except KeyError:
@@ -16,7 +18,7 @@ class GreekGetter:
 
 
 
 
 class EnglishGetter:
 class EnglishGetter:
-    """Simply echoes the msg ids"""     
+    """Simply echoes the msg ids"""
     def get(self, msgid):
     def get(self, msgid):
         return str(msgid)
         return str(msgid)
 
 

+ 3 - 0
flyweight.py

@@ -1,3 +1,6 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 """http://codesnipers.com/?q=python-flyweights"""
 """http://codesnipers.com/?q=python-flyweights"""
 
 
 import weakref
 import weakref

+ 10 - 7
graph_search.py

@@ -1,10 +1,13 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 class GraphSearch:
 class GraphSearch:
     """Graph search emulation in python, from source
     """Graph search emulation in python, from source
     http://www.python.org/doc/essays/graphs/"""
     http://www.python.org/doc/essays/graphs/"""
 
 
     def __init__(self, graph):
     def __init__(self, graph):
-        self.graph = graph 
-    
+        self.graph = graph
+
     def find_path(self, start, end, path=[]):
     def find_path(self, start, end, path=[]):
         self.start = start
         self.start = start
         self.end = end
         self.end = end
@@ -22,7 +25,7 @@ class GraphSearch:
                     return newpath
                     return newpath
         return None
         return None
 
 
-    def find_all_path(self, start, end, path=[]):            
+    def find_all_path(self, start, end, path=[]):
         self.start = start
         self.start = start
         self.end = end
         self.end = end
         self.path = path
         self.path = path
@@ -36,14 +39,14 @@ class GraphSearch:
             if node not in self.path:
             if node not in self.path:
                 newpaths = self.find_all_path(node, self.end, self.path)
                 newpaths = self.find_all_path(node, self.end, self.path)
                 for newpath in newpaths:
                 for newpath in newpaths:
-                    paths.append(newpath)                
+                    paths.append(newpath)
         return paths
         return paths
 
 
-    def find_shortest_path(self, start, end, path=[]):         
+    def find_shortest_path(self, start, end, path=[]):
         self.start = start
         self.start = start
         self.end = end
         self.end = end
         self.path = path
         self.path = path
-        
+
         self.path += [self.start]
         self.path += [self.start]
         if self.start == self.end:
         if self.start == self.end:
             return self.path
             return self.path
@@ -64,7 +67,7 @@ graph = {'A': ['B', 'C'],
          'C': ['D'],
          'C': ['D'],
          'D': ['C'],
          'D': ['C'],
          'E': ['F'],
          'E': ['F'],
-         'F': ['C']   
+         'F': ['C']
          }
          }
 
 
 #initialization of new graph search object
 #initialization of new graph search object

+ 3 - 0
iterator.py

@@ -1,3 +1,6 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 """http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
 """http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
 
 
 Implementation of the iterator pattern with a generator"""
 Implementation of the iterator pattern with a generator"""

+ 3 - 0
mediator.py

@@ -1,3 +1,6 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 """http://dpip.testingperspective.com/?p=28"""
 """http://dpip.testingperspective.com/?p=28"""
 
 
 import random
 import random

+ 4 - 1
memento.py

@@ -1,4 +1,7 @@
-"""code.activestate.com/recipes/413838-memento-closure/"""
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""http://code.activestate.com/recipes/413838-memento-closure/"""
 
 
 import copy
 import copy
 
 

+ 3 - 2
null.py

@@ -1,4 +1,5 @@
-#!/user/bin/env python 
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
 
 
 """http://code.activestate.com/recipes/68205-null-object-design-pattern/"""
 """http://code.activestate.com/recipes/68205-null-object-design-pattern/"""
 
 
@@ -72,7 +73,7 @@ def test():
     del n.attr1.attr2.attr3
     del n.attr1.attr2.attr3
 
 
     # representation and conversion to a string
     # representation and conversion to a string
-    
+
     assert repr(n) == '<Null>'
     assert repr(n) == '<Null>'
     assert str(n) == 'Null'
     assert str(n) == 'Null'
 
 

+ 4 - 1
observer.py

@@ -1,3 +1,6 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 """http://code.activestate.com/recipes/131499-observer-pattern/"""
 """http://code.activestate.com/recipes/131499-observer-pattern/"""
 
 
 
 
@@ -31,7 +34,7 @@ class Data(Subject):
     @property
     @property
     def data(self):
     def data(self):
         return self._data
         return self._data
-    
+
     @data.setter
     @data.setter
     def data(self, value):
     def data(self, value):
         self._data = value
         self._data = value

+ 3 - 0
pool.py

@@ -1,3 +1,6 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 """http://stackoverflow.com/questions/1514120/python-implementation-of-the-object-pool-design-pattern"""
 """http://stackoverflow.com/questions/1514120/python-implementation-of-the-object-pool-design-pattern"""
 
 
 
 

+ 3 - 0
prototype.py

@@ -1,3 +1,6 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 import copy
 import copy
 
 
 
 

+ 16 - 13
proxy.py

@@ -1,26 +1,29 @@
-import time 
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import time
 
 
 
 
 class SalesManager:
 class SalesManager:
-    def work(self):                         
-        print("Sales Manager working...")             
+    def work(self):
+        print("Sales Manager working...")
 
 
-    def talk(self):                         
-        print("Sales Manager ready to talk") 
+    def talk(self):
+        print("Sales Manager ready to talk")
 
 
 
 
 class Proxy:
 class Proxy:
-    def __init__(self):                         
-        self.busy = 'No'                         
-        self.sales = None             
+    def __init__(self):
+        self.busy = 'No'
+        self.sales = None
 
 
     def work(self):
     def work(self):
-        print("Proxy checking for Sales Manager availability")                         
-        if self.busy == 'No':                                      
-            self.sales = SalesManager()                                      
+        print("Proxy checking for Sales Manager availability")
+        if self.busy == 'No':
+            self.sales = SalesManager()
             time.sleep(2)
             time.sleep(2)
-            self.sales.talk()                         
-        else:                                      
+            self.sales.talk()
+        else:
             time.sleep(2)
             time.sleep(2)
             print("Sales Manager is busy")
             print("Sales Manager is busy")
 
 

+ 1 - 0
publish_subscribe.py

@@ -1,4 +1,5 @@
 #!/usr/bin/env python
 #!/usr/bin/env python
+# -*- coding: utf-8 -*-
 
 
 '''
 '''
 Reference: http://www.slideshare.net/ishraqabd/publish-subscribe-model-overview-13368808
 Reference: http://www.slideshare.net/ishraqabd/publish-subscribe-model-overview-13368808