Procházet zdrojové kódy

Fixed a number of pep8 violations.

Jeroen před 12 roky
rodič
revize
533c8680de
25 změnil soubory, kde provedl 306 přidání a 197 odebrání
  1. 12 1
      abstract_factory.py
  2. 8 1
      adapter.py
  3. 1 1
      borg.py
  4. 9 4
      bridge.py
  5. 9 3
      builder.py
  6. 7 1
      chain.py
  7. 3 2
      command.py
  8. 18 13
      composite.py
  9. 5 0
      decorator.py
  10. 6 1
      facade.py
  11. 4 1
      factory_method.py
  12. 6 4
      flyweight.py
  13. 12 11
      graph_search.py
  14. 7 4
      iterator.py
  15. 17 11
      mediator.py
  16. 72 69
      memento.py
  17. 12 9
      null.py
  18. 3 1
      observer.py
  19. 29 27
      pool.py
  20. 6 4
      prototype.py
  21. 9 6
      proxy.py
  22. 9 4
      state.py
  23. 10 6
      strategy.py
  24. 15 8
      template.py
  25. 17 5
      visitor.py

+ 12 - 1
abstract_factory.py

@@ -4,6 +4,7 @@
 
 import random
 
+
 class PetShop:
     """A pet shop"""
 
@@ -22,41 +23,51 @@ class PetShop:
         print("It says", pet.speak())
         print("It eats", self.pet_factory.get_food())
 
+
 # Stuff that our factory makes
 
 class Dog:
     def speak(self):
         return "woof"
+
     def __str__(self):
         return "Dog"
 
+
 class Cat:
     def speak(self):
         return "meow"
+
     def __str__(self):
         return "Cat"
 
+
 # Factory classes
 
 class DogFactory:
     def get_pet(self):
         return Dog()
+
     def get_food(self):
         return "dog food"
 
+
 class CatFactory:
     def get_pet(self):
         return Cat()
+
     def get_food(self):
         return "cat food"
 
+
 # Create the proper family
 def get_factory():
     """Let's be dynamic!"""
     return random.choice([DogFactory, CatFactory])()
 
+
 # Show pets with various factories
-if __name__== "__main__":
+if __name__ == "__main__":
     shop = PetShop()
     for i in range(3):
         shop.pet_factory = get_factory()

+ 8 - 1
adapter.py

@@ -2,6 +2,7 @@
 
 import os
 
+
 class Dog(object):
     def __init__(self):
         self.name = "Dog"
@@ -9,6 +10,7 @@ class Dog(object):
     def bark(self):
         return "woof!"
 
+
 class Cat(object):
     def __init__(self):
         self.name = "Cat"
@@ -16,6 +18,7 @@ class Cat(object):
     def meow(self):
         return "meow!"
 
+
 class Human(object):
     def __init__(self):
         self.name = "Human"
@@ -23,6 +26,7 @@ class Human(object):
     def speak(self):
         return "'hello'"
 
+
 class Car(object):
     def __init__(self):
         self.name = "Car"
@@ -30,6 +34,7 @@ class Car(object):
     def make_noise(self, octane_level):
         return "vroom%s" % ("!" * octane_level)
 
+
 class Adapter(object):
     """
     Adapts an object by replacing methods.
@@ -46,6 +51,7 @@ class Adapter(object):
         """All non-adapted calls are passed to the object"""
         return getattr(self.obj, attr)
 
+
 def main():
     objects = []
     dog = Dog()
@@ -55,11 +61,12 @@ def main():
     human = Human()
     objects.append(Adapter(human, dict(make_noise=human.speak)))
     car = Car()
-    car_noise = lambda : car.make_noise(3)
+    car_noise = lambda: car.make_noise(3)
     objects.append(Adapter(car, dict(make_noise=car_noise)))
 
     for obj in objects:
         print("A", obj.name, "goes", obj.make_noise())
 
+
 if __name__ == "__main__":
     main()

+ 1 - 1
borg.py

@@ -7,6 +7,7 @@ class Borg:
     def __str__(self):
         return self.state
 
+
 class YourBorg(Borg):
     pass
 
@@ -33,4 +34,3 @@ if __name__ == '__main__':
     print('rm1:', rm1)
     print('rm2:', rm2)
     print('rm3:', rm3)
-

+ 9 - 4
bridge.py

@@ -1,15 +1,18 @@
 # http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Bridge_Pattern#Python
 
+
 # ConcreteImplementor 1/2
 class DrawingAPI1:
     def drawCircle(self, x, y, radius):
         print('API1.circle at {}:{} radius {}'.format(x, y, radius))
- 
+
+
 # ConcreteImplementor 2/2
 class DrawingAPI2:
     def drawCircle(self, x, y, radius):
         print('API2.circle at {}:{} radius {}'.format(x, y, radius))
- 
+
+
 # Refined Abstraction
 class CircleShape:
     def __init__(self, x, y, radius, drawingAPI):
@@ -25,16 +28,18 @@ class CircleShape:
     # high-level i.e. Abstraction specific
     def resizeByPercentage(self, pct):
         self.__radius *= pct
- 
+
+
 def main():
     shapes = (
         CircleShape(1, 2, 3, DrawingAPI1()),
         CircleShape(5, 7, 11, DrawingAPI2())
-        )
+    )
  
     for shape in shapes:
         shape.resizeByPercentage(2.5)
         shape.draw()
  
+
 if __name__ == "__main__":
     main()

+ 9 - 3
builder.py

@@ -6,6 +6,7 @@
     https://gist.github.com/420905#file_builder_python.py
 """
 
+
 # Director
 class Director(object):
     def __init__(self):
@@ -19,6 +20,7 @@ class Director(object):
     def get_building(self):
         return self.builder.building
 
+
 # Abstract Builder
 class Builder(object):
     def __init__(self):
@@ -27,21 +29,24 @@ class Builder(object):
     def new_building(self):
         self.building = Building()
 
+
 # Concrete Builder
 class BuilderHouse(Builder):
     def build_floor(self):
-        self.building.floor ='One'
+        self.building.floor = 'One'
 
     def build_size(self):
         self.building.size = 'Big'
 
+
 class BuilderFlat(Builder):
     def build_floor(self):
-        self.building.floor ='More than One'
+        self.building.floor = 'More than One'
         
     def build_size(self):
         self.building.size = 'Small'
 
+
 # Product
 class Building(object):
     def __init__(self):
@@ -51,8 +56,9 @@ class Building(object):
     def __repr__(self):
         return 'Floor: %s | Size: %s' % (self.floor, self.size)
 
+
 # Client
-if __name__== "__main__":
+if __name__ == "__main__":
     director = Director()
     director.builder = BuilderHouse()
     director.construct_building()

+ 7 - 1
chain.py

@@ -1,9 +1,11 @@
 # http://www.testingperspective.com/wiki/doku.php/collaboration/chetan/designpatternsinpython/chain-of-responsibilitypattern
 
+
 class Handler:
     def successor(self, successor):
         self.successor = successor
 
+
 class ConcreteHandler1(Handler):
     def handle(self, request):
         if request > 0 and request <= 10:
@@ -11,6 +13,7 @@ class ConcreteHandler1(Handler):
         else:
             self.successor.handle(request)
  
+
 class ConcreteHandler2(Handler):
     def handle(self, request):
         if request > 10 and request <= 20:
@@ -18,6 +21,7 @@ class ConcreteHandler2(Handler):
         else:
             self.successor.handle(request)
  
+
 class ConcreteHandler3(Handler):
     def handle(self, request):
         if request > 20 and request <= 30:
@@ -25,6 +29,7 @@ class ConcreteHandler3(Handler):
         else:
             print('end of chain, no handler for {}'.format(request))
  
+
 class Client:
     def __init__(self):
         h1 = ConcreteHandler1()
@@ -38,5 +43,6 @@ class Client:
         for request in requests:
             h1.handle(request)
 
-if __name__== "__main__":
+
+if __name__ == "__main__":
     client = Client()

+ 3 - 2
command.py

@@ -1,5 +1,6 @@
 import os
 
+
 class MoveFileCommand(object):
     def __init__(self, src, dest):
         self.src = src
@@ -32,5 +33,5 @@ if __name__ == "__main__":
 
     # and can also be undone on will
     for cmd in undo_stack:
-        undo_stack.pop().undo() # Now it's bar.txt
-        undo_stack.pop().undo() # and back to foo.txt
+        undo_stack.pop().undo()  # Now it's bar.txt
+        undo_stack.pop().undo()  # and back to foo.txt

+ 18 - 13
composite.py

@@ -19,18 +19,20 @@ def normalize(val):
     to a Python object """
     
     if val.find('-') != -1:
-        val = val.replace('-','_')
+        val = val.replace('-', '_')
 
     return val
 
+
 def denormalize(val):
     """ De-normalize a string """
-    
+
     if val.find('_') != -1:
-        val = val.replace('_','-')
+        val = val.replace('_', '-')
 
     return val
 
+
 class SpecialDict(dict):
     """ A dictionary type which allows direct attribute
     access to its keys """
@@ -64,24 +66,25 @@ class SpecialDict(dict):
                 # New attribute
                 self[name] = value
         
+
 class CompositeDict(SpecialDict):
     """ A class which works like a hierarchical dictionary.
     This class is based on the Composite design-pattern """
-    
+
     ID = 0
-    
+
     def __init__(self, name=''):
 
         if name:
             self._name = name
         else:
-            self._name = ''.join(('id#',str(self.__class__.ID)))
+            self._name = ''.join(('id#', str(self.__class__.ID)))
             self.__class__.ID += 1
-        
+
         self._children = []
         # Link  back to father
         self._father = None
-        self[self._name] =  SpecialDict()
+        self[self._name] = SpecialDict()
 
     def __getattr__(self, name):
 
@@ -101,7 +104,8 @@ class CompositeDict(SpecialDict):
                     return child
                 else:
                     attr = getattr(self[self._name], name)
-                    if attr: return attr
+                    if attr:
+                        return attr
                     
                     raise AttributeError('no attribute named %s' % name)
 
@@ -306,17 +310,18 @@ class CompositeDict(SpecialDict):
             self._children.append(child)
             self.__setChildDict(child)
 
-if __name__=="__main__":
+
+if __name__ == "__main__":
     window = CompositeDict('Window')
     frame = window.addChild('Frame')
     tfield = frame.addChild('Text Field')
-    tfield.setAttribute('size','20')
+    tfield.setAttribute('size', '20')
     
     btn = frame.addChild('Button1')
-    btn.setAttribute('label','Submit')
+    btn.setAttribute('label', 'Submit')
 
     btn = frame.addChild('Button2')
-    btn.setAttribute('label','Browse')
+    btn.setAttribute('label', 'Browse')
 
     # print(window)
     # print(window.Frame)

+ 5 - 0
decorator.py

@@ -1,17 +1,22 @@
 # http://stackoverflow.com/questions/3118929/implementing-the-decorator-pattern-in-python
 
+
 class foo(object):
     def f1(self):
         print("original f1")
+
     def f2(self):
         print("original f2")
 
+
 class foo_decorator(object):
     def __init__(self, decoratee):
         self._decoratee = decoratee
+
     def f1(self):
         print("decorated f1")
         self._decoratee.f1()
+
     def __getattr__(self, name):
         return getattr(self._decoratee, name)
 

+ 6 - 1
facade.py

@@ -1,9 +1,10 @@
-'''http://dpip.testingperspective.com/?p=26'''
+"""http://dpip.testingperspective.com/?p=26"""
 
 import time
 
 SLEEP = 0.5
 
+
 # Complex Parts
 class TC1:
     def run(self):
@@ -17,6 +18,7 @@ class TC1:
         time.sleep(SLEEP)
         print("Test Finished\n")
 
+
 class TC2:
     def run(self):
         print("###### In Test 2 ######")
@@ -29,6 +31,7 @@ class TC2:
         time.sleep(SLEEP)
         print("Test Finished\n")
 
+
 class TC3:
     def run(self):
         print("###### In Test 3 ######")
@@ -41,6 +44,7 @@ class TC3:
         time.sleep(SLEEP)
         print("Test Finished\n")
 
+
 # Facade
 class TestRunner:
     def __init__(self):
@@ -52,6 +56,7 @@ class TestRunner:
     def runAll(self):
         [i.run() for i in self.tests]
 
+
 # Client
 if __name__ == '__main__':
     testrunner = TestRunner()

+ 4 - 1
factory_method.py

@@ -1,5 +1,6 @@
 #encoding=utf-8
-'''http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/'''
+"""http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/"""
+
 
 class GreekGetter:
     """A simple localizer a la gettext"""
@@ -13,11 +14,13 @@ class GreekGetter:
         except KeyError:
             return str(msgid)
 
+
 class EnglishGetter:
     """Simply echoes the msg ids"""     
     def get(self, msgid):
         return str(msgid)
 
+
 def get_localizer(language="English"):
     """The factory method"""
     languages = dict(English=EnglishGetter, Greek=GreekGetter)

+ 6 - 4
flyweight.py

@@ -1,13 +1,14 @@
-'''http://codesnipers.com/?q=python-flyweights'''
+"""http://codesnipers.com/?q=python-flyweights"""
 
 import weakref  
 
+
 class Card(object):
-    '''The object pool. Has builtin reference counting'''
+    """The object pool. Has builtin reference counting"""
     _CardPool = weakref.WeakValueDictionary() 
 
-    '''Flyweight implementation. If the object exists in the
-    pool just return it (instead of creating a new one)'''
+    """Flyweight implementation. If the object exists in the
+    pool just return it (instead of creating a new one)"""
     def __new__(cls, value, suit):         
         obj = Card._CardPool.get(value + suit, None)         
         if not obj:             
@@ -22,6 +23,7 @@ class Card(object):
     def __repr__(self):         
         return "<Card: %s%s>" % (self.value, self.suit)      
 
+
 if __name__ == '__main__':
     # comment __new__ and uncomment __init__ to see the difference
     c1 = Card('9', 'h')

+ 12 - 11
graph_search.py

@@ -1,6 +1,7 @@
 class GraphSearch:
-    """Graph search emulation in python, from source http://www.python.org/doc/essays/graphs/"""
-    
+    """Graph search emulation in python, from source
+    http://www.python.org/doc/essays/graphs/"""
+
     def __init__(self, graph):
         self.graph = graph 
     
@@ -8,8 +9,8 @@ class GraphSearch:
         self.start = start
         self.end = end
         self.path = path
-        
-        self.path+=[self.start]
+
+        self.path += [self.start]
         if self.start == self.end:
             return self.path
         if not self.graph.has_key(self.start):
@@ -20,30 +21,30 @@ class GraphSearch:
                 if newpath:
                     return newpath
         return None
-    
+
     def find_all_path(self, start, end, path=[]):            
         self.start = start
         self.end = end
         self.path = path
-        self.path+=[self.start]
+        self.path += [self.start]
         if self.start == self.end:
             return [self.path]
         if not self.graph.has_key(self.start):
             return []
-        paths=[]
+        paths = []
         for node in self.graph[self.start]:
             if node not in self.path:
                 newpaths = self.find_all_path(node, self.end, self.path)
                 for newpath in newpaths:
                     paths.append(newpath)                
         return paths
-    
+
     def find_shortest_path(self, start, end, path=[]):         
         self.start = start
         self.end = end
         self.path = path
         
-        self.path+=[self.start]
+        self.path += [self.start]
         if self.start == self.end:
             return self.path
         if not self.graph.has_key(self.start):
@@ -58,13 +59,13 @@ class GraphSearch:
         return shortest
 
 #example of graph usage
-graph = {'A':['B', 'C'],
+graph = {'A': ['B', 'C'],
          'B': ['C', 'D'],
          'C': ['D'],
          'D': ['C'],
          'E': ['F'],
          'F': ['C']   
-            }
+         }
 
 #inistialization of new graph search object
 graph1 = GraphSearch(graph)

+ 7 - 4
iterator.py

@@ -1,16 +1,19 @@
-'''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"""
+
+
 def count_to(count):
     """Counts by word numbers, up to a maximum of five"""
     numbers = ["one", "two", "three", "four", "five"]
-    # enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence
+    # enumerate() returns a tuple containing a count (from start which
+    # defaults to 0) and the values obtained from iterating over sequence
     for pos, number in zip(range(count), numbers):
         yield number
 
 # Test the generator
-count_to_two = lambda : count_to(2)
-count_to_five = lambda : count_to(5)
+count_to_two = lambda: count_to(2)
+count_to_five = lambda: count_to(5)
 
 print('Counting to two...')
 for number in count_to_two():

+ 17 - 11
mediator.py

@@ -1,8 +1,9 @@
-'''http://dpip.testingperspective.com/?p=28'''
+"""http://dpip.testingperspective.com/?p=28"""
 
 import time 
 
-class TC:             
+
+class TC:
     def __init__(self):                         
         self._tm = tm                         
         self._bProblem = 0             
@@ -27,13 +28,14 @@ class TC:
         else:                                      
             print("Test not executed. No tear down required.")             
 
-    def setTM(self,TM):                         
+    def setTM(self, TM):
         self._tm = tm             
 
     def setProblem(self, value):                         
         self._bProblem = value 
 
-class Reporter:             
+
+class Reporter:
     def __init__(self):                         
         self._tm = None             
 
@@ -45,10 +47,11 @@ class Reporter:
         print("Reporting the results of Test")                         
         time.sleep(1)             
 
-    def setTM(self,TM):                         
+    def setTM(self, TM):
         self._tm = tm 
 
-class DB:             
+
+class DB:
     def __init__(self):                         
         self._tm = None             
 
@@ -57,17 +60,18 @@ class DB:
         time.sleep(1)                         
         #Following code is to simulate a communication from DB to TC                         
         import random                         
-        if random.randrange(1,4) == 3:
+        if random.randrange(1, 4) == 3:
             return -1             
 
     def update(self):                         
         print("Updating the test results in Database")                         
         time.sleep(1)             
 
-    def setTM(self,TM):                         
+    def setTM(self, TM):
         self._tm = tm 
 
-class TestManager:             
+
+class TestManager:
     def __init__(self):                         
         self._reporter = None                         
         self._db = None                         
@@ -89,9 +93,10 @@ class TestManager:
         self._db.update()                         
         rvalue = self._reporter.report()             
 
-    def setTC(self,tc):                         
+    def setTC(self, tc):
         self._tc = tc 
 
+
 if __name__ == '__main__':             
     reporter = Reporter()             
     db = DB()             
@@ -101,7 +106,8 @@ if __name__ == '__main__':
     reporter.setTM(tm)             
     db.setTM(tm)             
     # For simplification we are looping on the same test.             
-    # Practically, it could be about various unique test classes and their objects             
+    # Practically, it could be about various unique test classes and their
+    # objects
     while (True):                         
         tc = TC()                         
         tc.setTM(tm)                         

+ 72 - 69
memento.py

@@ -1,91 +1,94 @@
-'''code.activestate.com/recipes/413838-memento-closure/'''
+"""code.activestate.com/recipes/413838-memento-closure/"""
 
 import copy
 
+
 def Memento(obj, deep=False):
-   state = (copy.copy, copy.deepcopy)[bool(deep)](obj.__dict__)
+    state = (copy.copy, copy.deepcopy)[bool(deep)](obj.__dict__)
+
+    def Restore():
+        obj.__dict__.clear()
+        obj.__dict__.update(state)
+    return Restore
 
-   def Restore():
-      obj.__dict__.clear()
-      obj.__dict__.update(state)
-   return Restore
 
 class Transaction:
-   """A transaction guard. This is really just 
+    """A transaction guard. This is really just
       syntactic suggar arount a memento closure.
-   """
-   deep = False
+      """
+    deep = False
+
+    def __init__(self, *targets):
+        self.targets = targets
+        self.Commit()
 
-   def __init__(self, *targets):
-      self.targets = targets
-      self.Commit()
+    def Commit(self):
+        self.states = [Memento(target, self.deep) for target in self.targets]
 
-   def Commit(self):
-      self.states = [Memento(target, self.deep) for target in self.targets]
+    def Rollback(self):
+        for st in self.states:
+            st()
 
-   def Rollback(self):
-      for st in self.states:
-         st()
 
 class transactional(object):
-   """Adds transactional semantics to methods. Methods decorated 
-      with @transactional will rollback to entry state upon exceptions.
-   """
-   def __init__(self, method):
-      self.method = method
-
-   def __get__(self, obj, T):
-      def transaction(*args, **kwargs):
-         state = Memento(obj)
-         try:
-            return self.method(obj, *args, **kwargs)
-         except:
-            state()
-            raise
-      return transaction
+    """Adds transactional semantics to methods. Methods decorated  with
+    @transactional will rollback to entry state upon exceptions.
+    """
+    def __init__(self, method):
+        self.method = method
+
+    def __get__(self, obj, T):
+        def transaction(*args, **kwargs):
+            state = Memento(obj)
+            try:
+                return self.method(obj, *args, **kwargs)
+            except:
+                state()
+                raise
+        return transaction
 
 
 class NumObj(object):
-   def __init__(self, value):
-      self.value = value
+    def __init__(self, value):
+        self.value = value
 
-   def __repr__(self):
-      return '<%s: %r>' % (self.__class__.__name__, self.value)
+    def __repr__(self):
+        return '<%s: %r>' % (self.__class__.__name__, self.value)
 
-   def Increment(self):
-      self.value += 1
+    def Increment(self):
+        self.value += 1
 
-   @transactional
-   def DoStuff(self):
-      self.value = '1111' # <- invalid value
-      self.Increment()    # <- will fail and rollback
+    @transactional
+    def DoStuff(self):
+        self.value = '1111'  # <- invalid value
+        self.Increment()     # <- will fail and rollback
 
 
 if __name__ == '__main__':
-   n = NumObj(-1)
-   print(n)
-   t = Transaction(n)
-   try:
-      for i in range(3):
-         n.Increment()
-         print(n)
-      t.Commit()
-      print('-- commited')
-      for i in range(3):
-         n.Increment()
-         print(n)
-      n.value += 'x' # will fail
-      print(n)
-   except:
-      t.Rollback()
-      print('-- rolled back')
-   print(n)
-   print('-- now doing stuff ...')
-   try:
-      n.DoStuff()
-   except:
-      print('-> doing stuff failed!')
-      import traceback
-      traceback.print_exc(0)
-      pass
-   print(n)
+    n = NumObj(-1)
+    print(n)
+    t = Transaction(n)
+    try:
+        for i in range(3):
+            n.Increment()
+            print(n)
+        t.Commit()
+        print('-- commited')
+        for i in range(3):
+            n.Increment()
+            print(n)
+        n.value += 'x'  # will fail
+        print(n)
+    except:
+        t.Rollback()
+        print('-- rolled back')
+    print(n)
+    print('-- now doing stuff ...')
+    try:
+        n.DoStuff()
+    except:
+        print('-> doing stuff failed!')
+        import traceback
+        traceback.print_exc(0)
+        pass
+    print(n)

+ 12 - 9
null.py

@@ -1,38 +1,40 @@
 #!/user/bin/env python 
 
-'''http://code.activestate.com/recipes/68205-null-object-design-pattern/'''
+"""http://code.activestate.com/recipes/68205-null-object-design-pattern/"""
+
 
 class Null:
     def __init__(self, *args, **kwargs):
-        "Ignore parameters."
+        """Ignore parameters."""
         return None
 
     def __call__(self, *args, **kwargs):
-        "Ignore method calls."
+        """Ignore method calls."""
         return self
 
     def __getattr__(self, mname):
-        "Ignore attribute requests."
+        """Ignore attribute requests."""
         return self
 
     def __setattr__(self, name, value):
-        "Ignore attribute setting."
+        """Ignore attribute setting."""
         return self
 
     def __delattr__(self, name):
-        "Ignore deleting attributes."
+        """Ignore deleting attributes."""
         return self
 
     def __repr__(self):
-        "Return a string representation."
+        """Return a string representation."""
         return "<Null>"
 
     def __str__(self):
-        "Convert to a string and return it."
+        """Convert to a string and return it."""
         return "Null"
 
+
 def test():
-    "Perform some decent tests, or rather: demos."
+    """Perform some decent tests, or rather: demos."""
 
     # constructing and calling
 
@@ -74,5 +76,6 @@ def test():
     assert repr(n) == '<Null>'
     assert str(n) == 'Null'
 
+
 if __name__ == '__main__':
     test()

+ 3 - 1
observer.py

@@ -1,4 +1,5 @@
-'''http://code.activestate.com/recipes/131499-observer-pattern/'''
+"""http://code.activestate.com/recipes/131499-observer-pattern/"""
+
 
 class Subject(object):
     def __init__(self):
@@ -76,5 +77,6 @@ def main():
     print("Setting Data 2 = 15")
     data2.data = 15
 
+
 if __name__ == '__main__':
     main()

+ 29 - 27
pool.py

@@ -1,29 +1,31 @@
-'''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"""
 
-class qObj():   
-    _q = None   
-    o = None    
 
-    def __init__(self, dQ, autoGet = False):       
-        self._q = dQ        
-        
-        if autoGet == True:           
-            self.o = self._q.get()    
+class qObj():
+    _q = None
+    o = None
 
-    def __enter__(self):       
-        if self.o == None:           
-            self.o = self._q.get()           
-        return self.o     
+    def __init__(self, dQ, autoGet = False):
+        self._q = dQ
 
-    def __exit__(self, type, value, traceback):       
-        if self.o != None:           
-            self._q.put(self.o)           
-            self.o = None    
+        if autoGet == True:
+            self.o = self._q.get()
+
+    def __enter__(self):
+        if self.o == None:
+            self.o = self._q.get()
+        return self.o
+
+    def __exit__(self, type, value, traceback):
+        if self.o != None:
+            self._q.put(self.o)
+            self.o = None
+
+    def __del__(self):
+        if self.o != None:
+            self._q.put(self.o)
+            self.o = None
 
-    def __del__(self):       
-        if self.o != None:           
-            self._q.put(self.o)           
-            self.o = None   
 
 if __name__ == "__main__":
     try:
@@ -31,15 +33,15 @@ if __name__ == "__main__":
     except:                     # python 2.x compatibility
         import Queue
 
-    def testObj(Q):       
-        someObj = qObj(Q, True)        
-        print('Inside func: {}'.format(someObj.o))    
+    def testObj(Q):
+        someObj = qObj(Q, True)
+        print('Inside func: {}'.format(someObj.o))
 
     aQ = Queue.Queue()
-    aQ.put("yam")    
+    aQ.put("yam")
 
-    with qObj(aQ) as obj:       
-        print("Inside with: {}".format(obj))    
+    with qObj(aQ) as obj:
+        print("Inside with: {}".format(obj))
 
     print('Outside with: {}'.format(aQ.get()))
 

+ 6 - 4
prototype.py

@@ -1,5 +1,6 @@
 from copy import deepcopy
 
+
 class Prototype:
     def __init__(self):
         self._objs = {}
@@ -20,14 +21,15 @@ class Prototype:
         obj.__dict__.update(attr)
         return obj
 
+
 if __name__ == '__main__':
     class A:
         pass 
 
-    a=A()
-    prototype=Prototype() 
-    prototype.registerObject("a",a)
-    b=prototype.clone("a",a=1,b=2,c=3)
+    a = A()
+    prototype = Prototype()
+    prototype.registerObject("a", a)
+    b = prototype.clone("a", a=1, b=2, c=3)
 
     print(a)
     print(b.a, b.b, b.c)

+ 9 - 6
proxy.py

@@ -1,26 +1,29 @@
 import time 
 
-class SalesManager:             
+
+class SalesManager:
     def work(self):                         
         print("Sales Manager working...")             
 
     def talk(self):                         
         print("Sales Manager ready to talk") 
 
-class Proxy:             
+
+class Proxy:
     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()                                      
-            time.sleep(2);                                      
+            time.sleep(2)
             self.sales.talk()                         
         else:                                      
-            time.sleep(2);                                      
-            print("Sales Manager is busy") 
+            time.sleep(2)
+            print("Sales Manager is busy")
+
 
 if __name__ == '__main__':
     p = Proxy()

+ 9 - 4
state.py

@@ -2,7 +2,8 @@
 
 '''http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/'''
 
-class State(object):     
+
+class State(object):
     """Base state. This is to share functionality"""      
 
     def scan(self):         
@@ -12,7 +13,8 @@ class State(object):
             self.pos = 0         
         print("Scanning... Station is", self.stations[self.pos], self.name)  
 
-class AmState(State):     
+
+class AmState(State):
     def __init__(self, radio):         
         self.radio = radio         
         self.stations = ["1250", "1380", "1510"]         
@@ -23,7 +25,8 @@ class AmState(State):
         print("Switching to FM")         
         self.radio.state = self.radio.fmstate  
 
-class FmState(State):     
+
+class FmState(State):
     def __init__(self, radio):         
         self.radio = radio         
         self.stations = ["81.3", "89.1", "103.9"]         
@@ -34,7 +37,8 @@ class FmState(State):
         print("Switching to AM")         
         self.radio.state = self.radio.amstate  
 
-class Radio(object):     
+
+class Radio(object):
     """A radio.     It has a scan button, and an AM/FM toggle switch."""      
     def __init__(self):         
         """We have an AM state and an FM state"""          
@@ -48,6 +52,7 @@ class Radio(object):
     def scan(self):         
         self.state.scan()  
 
+
 # Test our radio out
 if __name__ == '__main__':
     radio = Radio() 

+ 10 - 6
strategy.py

@@ -1,24 +1,28 @@
-'''http://stackoverflow.com/questions/963965/how-is-this-strategy-pattern-written-in-python-the-sample-in-wikipedia'''
+"""http://stackoverflow.com/questions/963965/how-is-this-strategy-pattern-written-in-python-the-sample-in-wikipedia"""
 
 import types  
 
-class StrategyExample:      
+
+class StrategyExample:
 
     def __init__(self, func=None):         
         self.name = "Strategy Example 0"         
-        if func :              
+        if func:
             self.execute = types.MethodType(func, self)      
 
     def execute(self):         
         print(self.name)   
 
-def executeReplacement1(self):         
+
+def executeReplacement1(self):
     print(self.name + " from execute 1")   
 
-def executeReplacement2(self):          
+
+def executeReplacement2(self):
     print(self.name + " from execute 2")  
 
-if __name__ == "__main__":      
+
+if __name__ == "__main__":
     strat0 = StrategyExample()     
 
     strat1 = StrategyExample(executeReplacement1)     

+ 15 - 8
template.py

@@ -1,38 +1,45 @@
-'''http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/'''
+"""http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/"""
 
 """An example of the Template pattern in Python"""  
 
 ingredients = "spam eggs apple"
 line = '-' * 10
 
-# Skeletons 
+
+# Skeletons
 def iter_elements(getter, action):     
     """Template skeleton that iterates items"""      
     for element in getter():         
         action(element)     
         print(line)  
 
-def rev_elements(getter, action):     
+
+def rev_elements(getter, action):
     """Template skeleton that iterates items in reverse order"""      
     for element in getter()[::-1]:         
         action(element)     
         print(line)  
 
-# Getters 
+
+# Getters
 def get_list():     
     return ingredients.split()  
 
-def get_lists():     
+
+def get_lists():
     return [list(x) for x in ingredients.split()]  
 
-# Actions 
+
+# Actions
 def print_item(item):     
     print(item)  
 
-def reverse_item(item):     
+
+def reverse_item(item):
     print(item[::-1])  
 
-# Makes templates 
+
+# Makes templates
 def make_template(skeleton, getter, action):     
     """Instantiate a template method with getter and action"""     
     def template():         

+ 17 - 5
visitor.py

@@ -1,9 +1,21 @@
-'''http://peter-hoffmann.com/2010/extrinsic-visitor-pattern-python-inheritance.html'''
+"""http://peter-hoffmann.com/2010/extrinsic-visitor-pattern-python-inheritance.html"""
+
+
+class Node(object):
+    pass
+
+
+class A(Node):
+    pass
+
+
+class B(Node):
+    pass
+
+
+class C(A, B):
+    pass
 
-class Node(object): pass
-class A(Node): pass
-class B(Node): pass
-class C(A,B): pass
 
 class Visitor(object):
     def visit(self, node, *args, **kwargs):