diff --git a/3-tier.py b/3-tier.py
index a1cd30c1..c1309fdc 100644
--- a/3-tier.py
+++ b/3-tier.py
@@ -17,7 +17,6 @@ def __get__(self, obj, klas):
class BusinessLogic(object):
-
""" Business logic holding data store instances """
data = Data()
@@ -61,6 +60,7 @@ def main():
ui.get_product_information('milk')
ui.get_product_information('arepas')
+
if __name__ == '__main__':
main()
diff --git a/abstract_factory.py b/abstract_factory.py
index a32c067e..71360e8b 100644
--- a/abstract_factory.py
+++ b/abstract_factory.py
@@ -7,8 +7,8 @@
import random
-class PetShop:
+class PetShop:
"""A pet shop"""
def __init__(self, animal_factory=None):
@@ -28,7 +28,6 @@ def show_pet(self):
# Stuff that our factory makes
class Dog:
-
def speak(self):
return "woof"
@@ -37,7 +36,6 @@ def __str__(self):
class Cat:
-
def speak(self):
return "meow"
@@ -48,7 +46,6 @@ def __str__(self):
# Factory classes
class DogFactory:
-
def get_pet(self):
return Dog()
@@ -57,13 +54,13 @@ def get_food(self):
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!"""
diff --git a/adapter.py b/adapter.py
index fedbd8c1..374d01fb 100644
--- a/adapter.py
+++ b/adapter.py
@@ -3,23 +3,27 @@
"""http://ginstrom.com/scribbles/2008/11/06/generic-adapter-class-in-python/"""
-import os
class Dog(object):
def __init__(self):
self.name = "Dog"
+
def bark(self):
return "woof!"
+
class Cat(object):
def __init__(self):
self.name = "Cat"
+
def meow(self):
return "meow!"
+
class Human(object):
def __init__(self):
self.name = "Human"
+
def speak(self):
return "'hello'"
@@ -27,12 +31,12 @@ def speak(self):
class Car(object):
def __init__(self):
self.name = "Car"
+
def make_noise(self, octane_level):
return "vroom{0}".format("!" * octane_level)
class Adapter(object):
-
"""
Adapts an object by replacing methods.
Usage:
diff --git a/borg.py b/borg.py
index 0c464022..5fa69172 100644
--- a/borg.py
+++ b/borg.py
@@ -16,6 +16,7 @@ def __str__(self):
class YourBorg(Borg):
pass
+
if __name__ == '__main__':
rm1 = Borg()
rm2 = Borg()
diff --git a/bridge.py b/bridge.py
index 1c3c0747..2330f084 100644
--- a/bridge.py
+++ b/bridge.py
@@ -6,21 +6,18 @@
# ConcreteImplementor 1/2
class DrawingAPI1(object):
-
def draw_circle(self, x, y, radius):
print('API1.circle at {}:{} radius {}'.format(x, y, radius))
# ConcreteImplementor 2/2
class DrawingAPI2(object):
-
def draw_circle(self, x, y, radius):
print('API2.circle at {}:{} radius {}'.format(x, y, radius))
# Refined Abstraction
class CircleShape(object):
-
def __init__(self, x, y, radius, drawing_api):
self._x = x
self._y = y
diff --git a/builder.py b/builder.py
index 3b04412d..47101059 100644
--- a/builder.py
+++ b/builder.py
@@ -9,7 +9,6 @@
# Director
class Director(object):
-
def __init__(self):
self.builder = None
@@ -24,7 +23,6 @@ def get_building(self):
# Abstract Builder
class Builder(object):
-
def __init__(self):
self.building = None
@@ -34,7 +32,6 @@ def new_building(self):
# Concrete Builder
class BuilderHouse(Builder):
-
def build_floor(self):
self.building.floor = 'One'
@@ -43,7 +40,6 @@ def build_size(self):
class BuilderFlat(Builder):
-
def build_floor(self):
self.building.floor = 'More than One'
@@ -53,7 +49,6 @@ def build_size(self):
# Product
class Building(object):
-
def __init__(self):
self.floor = None
self.size = None
diff --git a/catalog.py b/catalog.py
index 8bfdf921..c3f7eea4 100644
--- a/catalog.py
+++ b/catalog.py
@@ -10,7 +10,6 @@
class Catalog():
-
"""
catalog of multiple static methods that are executed depending on an init
parameter
@@ -22,7 +21,7 @@ def __init__(self, param):
# to be executed but that will be also used to store possible param
# value
self._static_method_choices = {'param_value_1': self._static_method_1,
- 'param_value_2': self._static_method_2}
+ 'param_value_2': self._static_method_2}
# simple test to validate param value
if param in self._static_method_choices.keys():
@@ -57,6 +56,7 @@ def main():
test = Catalog('param_value_2')
test.main_method()
+
if __name__ == "__main__":
main()
diff --git a/chain.py b/chain.py
index 6698f8f9..9bc56997 100644
--- a/chain.py
+++ b/chain.py
@@ -3,39 +3,42 @@
"""http://www.testingperspective.com/wiki/doku.php/collaboration/chetan/designpatternsinpython/chain-of-responsibilitypattern"""
+
class Handler:
- def __init__(self,successor):
+ def __init__(self, successor):
self._successor = successor;
- def handle(self,request):
+
+ def handle(self, request):
i = self._handle(request)
- if not i:
+ if not i:
self._successor.handle(request)
+
def _handle(self, request):
raise NotImplementedError('Must provide implementation in subclass.')
class ConcreteHandler1(Handler):
-
def _handle(self, request):
if 0 < request <= 10:
print('request {} handled in handler 1'.format(request))
return True
-
+
+
class ConcreteHandler2(Handler):
-
def _handle(self, request):
if 10 < request <= 20:
print('request {} handled in handler 2'.format(request))
return True
-
+
+
class ConcreteHandler3(Handler):
-
def _handle(self, request):
if 20 < request <= 30:
print('request {} handled in handler 3'.format(request))
return True
+
+
class DefaultHandler(Handler):
-
def _handle(self, request):
print('end of chain, no handler for {}'.format(request))
return True
@@ -44,6 +47,7 @@ def _handle(self, request):
class Client:
def __init__(self):
self.handler = ConcreteHandler1(ConcreteHandler3(ConcreteHandler2(DefaultHandler(None))))
+
def delegate(self, requests):
for request in requests:
self.handler.handle(request)
diff --git a/chaining_method.py b/chaining_method.py
index e0374761..086cd022 100644
--- a/chaining_method.py
+++ b/chaining_method.py
@@ -2,7 +2,6 @@
# -*- coding: utf-8 -*-
class Person(object):
-
def __init__(self, name, action):
self.name = name
self.action = action
@@ -11,8 +10,8 @@ def do_action(self):
print(self.name, self.action.name, end=' ')
return self.action
-class Action(object):
+class Action(object):
def __init__(self, name):
self.name = name
@@ -23,8 +22,8 @@ def amount(self, val):
def stop(self):
print('then stop')
-if __name__ == '__main__':
+if __name__ == '__main__':
move = Action('move')
person = Person('Jack', move)
person.do_action().amount('5m').stop()
diff --git a/command.py b/command.py
index 727f42cb..c0d91be5 100644
--- a/command.py
+++ b/command.py
@@ -5,7 +5,6 @@
class MoveFileCommand(object):
-
def __init__(self, src, dest):
self.src = src
self.dest = dest
@@ -34,6 +33,7 @@ def main():
for cmd in reversed(command_stack):
cmd.undo()
+
if __name__ == "__main__":
main()
diff --git a/composite.py b/composite.py
index 9b8cc56f..08a35100 100644
--- a/composite.py
+++ b/composite.py
@@ -37,7 +37,6 @@ def denormalize(val):
class SpecialDict(dict):
-
""" A dictionary type which allows direct attribute
access to its keys """
@@ -72,7 +71,6 @@ def __setattr__(self, name, value):
class CompositeDict(SpecialDict):
-
""" A class which works like a hierarchical dictionary.
This class is based on the Composite design-pattern """
diff --git a/decorator.py b/decorator.py
index ce96f315..bd760d5b 100644
--- a/decorator.py
+++ b/decorator.py
@@ -8,6 +8,7 @@ def makebold(fn):
@wraps(fn)
def wrapped():
return "" + fn() + ""
+
return wrapped
@@ -15,6 +16,7 @@ def makeitalic(fn):
@wraps(fn)
def wrapped():
return "" + fn() + ""
+
return wrapped
@@ -24,6 +26,7 @@ def hello():
"""a decorated hello world"""
return "hello world"
+
if __name__ == '__main__':
print('result:{} name:{} doc:{}'.format(hello(), hello.__name__, hello.__doc__))
diff --git a/facade.py b/facade.py
index 77197dc3..027b6be9 100644
--- a/facade.py
+++ b/facade.py
@@ -8,7 +8,6 @@
# Complex Parts
class TC1:
-
def run(self):
print("###### In Test 1 ######")
time.sleep(SLEEP)
@@ -22,7 +21,6 @@ def run(self):
class TC2:
-
def run(self):
print("###### In Test 2 ######")
time.sleep(SLEEP)
@@ -36,7 +34,6 @@ def run(self):
class TC3:
-
def run(self):
print("###### In Test 3 ######")
time.sleep(SLEEP)
@@ -51,7 +48,6 @@ def run(self):
# Facade
class TestRunner:
-
def __init__(self):
self.tc1 = TC1()
self.tc2 = TC2()
diff --git a/factory_method.py b/factory_method.py
index c21e3960..c69e0a1d 100644
--- a/factory_method.py
+++ b/factory_method.py
@@ -5,7 +5,6 @@
class GreekGetter:
-
"""A simple localizer a la gettext"""
def __init__(self):
@@ -20,7 +19,6 @@ def get(self, msgid):
class EnglishGetter:
-
"""Simply echoes the msg ids"""
def get(self, msgid):
diff --git a/flyweight.py b/flyweight.py
index efa48981..b18331bd 100644
--- a/flyweight.py
+++ b/flyweight.py
@@ -7,12 +7,12 @@
class Card(object):
-
"""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)"""
+
def __new__(cls, value, suit):
obj = Card._CardPool.get(value + suit, None)
if not obj:
@@ -22,7 +22,7 @@ def __new__(cls, value, suit):
return obj
# def __init__(self, value, suit):
- # self.value, self.suit = value, suit
+ # self.value, self.suit = value, suit
def __repr__(self):
return "" % (self.value, self.suit)
diff --git a/graph_search.py b/graph_search.py
index e76d2e39..537d20ba 100644
--- a/graph_search.py
+++ b/graph_search.py
@@ -3,7 +3,6 @@
class GraphSearch:
-
"""Graph search emulation in python, from source
http://www.python.org/doc/essays/graphs/"""
@@ -75,7 +74,6 @@ def find_shortest_path(self, start, end, path=None):
# initialization of new graph search object
graph1 = GraphSearch(graph)
-
print(graph1.find_path('A', 'D'))
print(graph1.find_all_path('A', 'D'))
print(graph1.find_shortest_path('A', 'D'))
diff --git a/iterator.py b/iterator.py
index 3aa36b8d..e0692cca 100644
--- a/iterator.py
+++ b/iterator.py
@@ -22,16 +22,16 @@ def count_to(count):
for number in count_to_two():
print(number, end=' ')
-print()
+ print()
-print('Counting to five...')
-for number in count_to_five():
- print(number, end=' ')
+ print('Counting to five...')
+ for number in count_to_five():
+ print(number, end=' ')
-print()
+ print()
-### OUTPUT ###
-# Counting to two...
-# one two
-# Counting to five...
-# one two three four five
+ ### OUTPUT ###
+ # Counting to two...
+ # one two
+ # Counting to five...
+ # one two three four five
diff --git a/mediator.py b/mediator.py
index 82a2886f..f8b8cd4b 100644
--- a/mediator.py
+++ b/mediator.py
@@ -8,7 +8,6 @@
class TC:
-
def __init__(self):
self._tm = None
self._bProblem = 0
@@ -41,7 +40,6 @@ def setProblem(self, value):
class Reporter:
-
def __init__(self):
self._tm = None
@@ -58,7 +56,6 @@ def setTM(self, tm):
class DB:
-
def __init__(self):
self._tm = None
@@ -78,7 +75,6 @@ def setTM(self, tm):
class TestManager:
-
def __init__(self):
self._reporter = None
self._db = None
diff --git a/memento.py b/memento.py
index 42034658..e7e596a7 100644
--- a/memento.py
+++ b/memento.py
@@ -12,11 +12,11 @@ def Memento(obj, deep=False):
def Restore():
obj.__dict__.clear()
obj.__dict__.update(state)
+
return Restore
class Transaction:
-
"""A transaction guard. This is really just
syntactic suggar arount a memento closure.
"""
@@ -35,7 +35,6 @@ def Rollback(self):
class transactional(object):
-
"""Adds transactional semantics to methods. Methods decorated with
@transactional will rollback to entry state upon exceptions.
"""
@@ -51,11 +50,11 @@ def transaction(*args, **kwargs):
except:
state()
raise
+
return transaction
class NumObj(object):
-
def __init__(self, value):
self.value = value
@@ -68,7 +67,7 @@ def Increment(self):
@transactional
def DoStuff(self):
self.value = '1111' # <- invalid value
- self.Increment() # <- will fail and rollback
+ self.Increment() # <- will fail and rollback
if __name__ == '__main__':
@@ -97,6 +96,7 @@ def DoStuff(self):
print('-> doing stuff failed!')
import sys
import traceback
+
traceback.print_exc(file=sys.stdout)
pass
print(n)
@@ -115,7 +115,7 @@ def DoStuff(self):
# -- now doing stuff ...
# -> doing stuff failed!
# Traceback (most recent call last):
-# File "memento.py", line 91, in
+# File "memento.py", line 91, in
# n.DoStuff()
# File "memento.py", line 47, in transaction
# return self.method(obj, *args, **kwargs)
diff --git a/mvc.py b/mvc.py
index 8087bdab..fbed2932 100644
--- a/mvc.py
+++ b/mvc.py
@@ -3,7 +3,6 @@
class Model(object):
-
products = {
'milk': {'price': 1.50, 'quantity': 10},
'eggs': {'price': 0.20, 'quantity': 100},
@@ -12,7 +11,6 @@ class Model(object):
class View(object):
-
def product_list(self, product_list):
print('PRODUCT LIST:')
for product in product_list:
@@ -30,7 +28,6 @@ def product_not_found(self, product):
class Controller(object):
-
def __init__(self):
self.model = Model()
self.view = View()
@@ -48,7 +45,6 @@ def get_product_information(self, product):
if __name__ == '__main__':
-
controller = Controller()
controller.get_product_list()
controller.get_product_information('cheese')
diff --git a/observer.py b/observer.py
index 4ce1aed6..b5409e10 100644
--- a/observer.py
+++ b/observer.py
@@ -5,7 +5,6 @@
class Subject(object):
-
def __init__(self):
self._observers = []
@@ -27,7 +26,6 @@ def notify(self, modifier=None):
# Example usage
class Data(Subject):
-
def __init__(self, name=''):
Subject.__init__(self)
self.name = name
@@ -44,14 +42,12 @@ def data(self, value):
class HexViewer:
-
def update(self, subject):
print('HexViewer: Subject %s has data 0x%x' %
(subject.name, subject.data))
class DecimalViewer:
-
def update(self, subject):
print('DecimalViewer: Subject %s has data %d' %
(subject.name, subject.data))
diff --git a/pool.py b/pool.py
index ec1107ba..c6e31950 100644
--- a/pool.py
+++ b/pool.py
@@ -5,7 +5,6 @@
class QueueObject():
-
def __init__(self, queue, auto_get=False):
self._queue = queue
self.object = self._queue.get() if auto_get else None
diff --git a/prototype.py b/prototype.py
index 2f2a14a8..5c32359a 100644
--- a/prototype.py
+++ b/prototype.py
@@ -5,7 +5,6 @@
class Prototype:
-
def __init__(self):
self._objects = {}
@@ -43,6 +42,7 @@ def main():
c = prototype.clone('objecta', x=1, y=2, garbage=[88, 1])
print([str(i) for i in (a, b, c)])
+
if __name__ == '__main__':
main()
diff --git a/proxy.py b/proxy.py
index 4c5b4cc0..1400eb15 100644
--- a/proxy.py
+++ b/proxy.py
@@ -5,7 +5,6 @@
class SalesManager:
-
def work(self):
print("Sales Manager working...")
@@ -14,7 +13,6 @@ def talk(self):
class Proxy:
-
def __init__(self):
self.busy = 'No'
self.sales = None
diff --git a/publish_subscribe.py b/publish_subscribe.py
index e88dd4f3..fd74eb6e 100644
--- a/publish_subscribe.py
+++ b/publish_subscribe.py
@@ -8,7 +8,6 @@
class Provider:
-
def __init__(self):
self.msg_queue = []
self.subscribers = {}
@@ -35,7 +34,6 @@ def update(self):
class Publisher:
-
def __init__(self, msg_center):
self.provider = msg_center
@@ -44,7 +42,6 @@ def publish(self, msg):
class Subscriber:
-
def __init__(self, name, msg_center):
self.name = name
self.provider = msg_center
diff --git a/state.py b/state.py
index 5f4ef41e..7785c890 100644
--- a/state.py
+++ b/state.py
@@ -4,7 +4,6 @@
class State(object):
-
"""Base state. This is to share functionality"""
def scan(self):
@@ -16,7 +15,6 @@ def scan(self):
class AmState(State):
-
def __init__(self, radio):
self.radio = radio
self.stations = ["1250", "1380", "1510"]
@@ -29,7 +27,6 @@ def toggle_amfm(self):
class FmState(State):
-
def __init__(self, radio):
self.radio = radio
self.stations = ["81.3", "89.1", "103.9"]
@@ -42,7 +39,6 @@ def toggle_amfm(self):
class Radio(object):
-
"""A radio. It has a scan button, and an AM/FM toggle switch."""
def __init__(self):
diff --git a/strategy.py b/strategy.py
index 8c7a9b5a..b3131b09 100644
--- a/strategy.py
+++ b/strategy.py
@@ -12,7 +12,6 @@
class StrategyExample:
-
def __init__(self, func=None):
self.name = 'Strategy Example 0'
if func is not None:
diff --git a/template.py b/template.py
index 42e7377e..26e6f5f6 100644
--- a/template.py
+++ b/template.py
@@ -42,8 +42,10 @@ def reverse_item(item):
# Makes templates
def make_template(skeleton, getter, action):
"""Instantiate a template method with getter and action"""
+
def template():
skeleton(getter, action)
+
return template
# Create our template functions
diff --git a/visitor.py b/visitor.py
index ca45102e..48205e74 100644
--- a/visitor.py
+++ b/visitor.py
@@ -18,7 +18,6 @@ class C(A, B):
class Visitor(object):
-
def visit(self, node, *args, **kwargs):
meth = None
for cls in node.__class__.__mro__: