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
 ===============
 
-A collection of design patterns implemented (by other people) in python
+A collection of design patterns implemented (by other people) in python.
 
 Current Patterns:
 
-* 3-tier		
-* composite		
+* 3-tier
+* composite
 * mvc
-* decorator		
+* decorator
 * null
-* facade		
+* facade
 * observer
-* abstract_factory	
-* factory_method	
+* abstract_factory
+* factory_method
 * pool
-* adapter		
-* flyweight		
+* adapter
+* flyweight
 * prototype
-* borg					
+* borg
 * proxy
-* bridge		
-* graph_search		
+* bridge
+* graph_search
 * state
-* builder		
-* iterator		
+* builder
+* iterator
 * strategy
-* chain		
-* mediator		
+* chain
+* mediator
 * template
-* command		
-* memento		
+* command
+* memento
 * 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/
 
 """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
 

+ 3 - 0
borg.py

@@ -1,3 +1,6 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 class Borg:
     __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
@@ -20,11 +23,11 @@ class CircleShape(object):
         self._y = y
         self._radius = radius
         self._drawing_api = drawing_api
- 
+
     # low-level i.e. Implementation specific
     def draw(self):
         self._drawing_api.draw_circle(self._x, self._y, self._radius)
- 
+
     # high-level i.e. Abstraction specific
     def scale(self, pct):
         self._radius *= pct
@@ -35,11 +38,11 @@ def main():
         CircleShape(1, 2, 3, DrawingAPI1()),
         CircleShape(5, 7, 11, DrawingAPI2())
     )
- 
+
     for shape in shapes:
         shape.scale(2.5)
         shape.draw()
- 
+
 
 if __name__ == '__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
 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:

+ 4 - 1
command.py

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

+ 3 - 0
facade.py

@@ -1,3 +1,6 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 """http://dpip.testingperspective.com/?p=26"""
 
 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/"""
 
 
@@ -8,7 +10,7 @@ class GreekGetter:
         self.trans = dict(dog="σκύλος", cat="γάτα")
 
     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:
             return self.trans[msgid]
         except KeyError:
@@ -16,7 +18,7 @@ class GreekGetter:
 
 
 class EnglishGetter:
-    """Simply echoes the msg ids"""     
+    """Simply echoes the msg ids"""
     def get(self, 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"""
 
 import weakref

+ 10 - 7
graph_search.py

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

+ 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/"""
 
@@ -72,7 +73,7 @@ def test():
     del n.attr1.attr2.attr3
 
     # representation and conversion to a string
-    
+
     assert repr(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/"""
 
 
@@ -31,7 +34,7 @@ class Data(Subject):
     @property
     def data(self):
         return self._data
-    
+
     @data.setter
     def data(self, 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"""
 
 

+ 3 - 0
prototype.py

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

+ 16 - 13
proxy.py

@@ -1,26 +1,29 @@
-import time 
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import time
 
 
 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:
-    def __init__(self):                         
-        self.busy = 'No'                         
-        self.sales = None             
+    def __init__(self):
+        self.busy = 'No'
+        self.sales = None
 
     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)
-            self.sales.talk()                         
-        else:                                      
+            self.sales.talk()
+        else:
             time.sleep(2)
             print("Sales Manager is busy")
 

+ 1 - 0
publish_subscribe.py

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