# Simple tool for making class-like objects using closures in Python 3
#
# Advantages:
# * cleaner coding style
# * faster internal references
# * faster external calls - no bound methods or rewriting arg tuples
# * easy to delegate work to other objects
#
# Disadvantages:
# * need setter methods to update attributes
# * inheritance is not supported
# * slower calls to special methods
# * there is no "self"
# * limited support for help()
import sys
class Object:
'Holder for anything you want to attach to it'
# The Python interpreter looks for special methods in the class dictionary
# Add support for them by dispatching them back to the instance methods
for sm in '''__len__ __bool__ __repr__ __str__ __iter__ __next__
__getitem__ __setitem__ __delitem__ __contains__
__eq__ __ne__ __lt__ __le__ __gt__ __ge__ __hash__
__add__ __mul__ __sub__ __truediv__ __floordiv__ __mod__
__pow__ __and__ __or__ __xor__ __invert__ __pos__ __neg__
__int__ __index__ __format__ __sizeof__
__call__ __enter__ __exit__ __reduce__ '''.split():
setattr(Object, sm, lambda self, *args, sm=sm: self.__dict__[sm](*args))
def classify(local_dict=None):
'Move local definitions to an instance dictionary'
o = Object()
if local_dict is None:
local_dict = sys._getframe(1).f_locals
vars(o).update(local_dict)
return o
############################################################################
### Simple example #######################################################
def Animal(name):
'Animal-like class'
def speak():
print('I am', name)
def set_name(newname):
nonlocal name
name = newname
def __getitem__(key):
return '%s is %sing' % (name, key.title())
return classify()
d = Animal('Fido')
d.speak()
d.set_name('Max')
d.speak()
print(d.name)
print(d['fetch'])
############################################################################
### Practical example ####################################################
def PriorityQueue(initial_tasklist):
'Retrieve tasks by priority. Tasks can be removed or reprioritized.'
from heapq import heappush, heappop
pq = [] # list of entries arranged in a heap
entry_finder = {} # mapping of tasks to entries
REMOVED = object() # placeholder for a removed task
count = 0 # unique sequence count
def add(task, priority=0):
'Add a new task or update the priority of an existing task'
nonlocal count
if task in entry_finder:
remove(task)
entry = [priority, count, task]
entry_finder[task] = entry
heappush(pq, entry)
count += 1
def remove(task):
'Mark an existing task as REMOVED. Raise KeyError if not found.'
entry = entry_pop(task)
entry[-1] = REMOVED
def pop():
'Remove and return the lowest priority task. Raise KeyError if empty.'
while pq:
priority, count, task = heappop(pq)
if task is not REMOVED:
del entry_finder[task]
return task
raise KeyError('pop from an empty priority queue')
def __iter__():
'Show task in order of priority'
pq.sort()
for priority, count, task in pq:
if task is not REMOVED:
yield task
def __repr__():
return 'PriorityQueue()'
def __str__():
return 'PriorityQueue with %d pending tasks' % __len__()
# Some work can delegated to another object
__contains__ = entry_finder.__contains__
__len__ = entry_finder.__len__
entry_pop = entry_finder.pop
for task, priority in initial_tasklist:
add(task, priority)
return classify()
if __name__ == '__main__':
# Note: Client code is written normally. It makes no difference
# whether a PriorityQueue was implemented as a regular class or
# implemented using closures.
todo = PriorityQueue([('fish', 5), ('play', 3)])
todo.add('code', 1)
todo.add('sleep', 6)
print(list(todo))
print('Pop the topmost task: %r' % todo.pop())
print("Deprioritize 'play'")
todo.add('play', 10)
todo.remove('sleep')
print(len(todo))
print(list(todo))
print(todo)
print('fish' in todo)
help(PriorityQueue)
help(todo.add)
Diff to Previous Revision
--- revision 6 2012-04-03 01:42:02
+++ revision 7 2012-04-07 21:49:53
@@ -1,23 +1,36 @@
# Simple tool for making class-like objects using closures in Python 3
#
# Advantages:
-# * cleaner coding style -- internal references use "someattr" instead of "self.someattr"
+# * cleaner coding style
# * faster internal references
# * faster external calls - no bound methods or rewriting arg tuples
-# * attributes are automatically "private"
+# * easy to delegate work to other objects
#
# Disadvantages:
-# * no direct access to attributes
-# * current version doesn't support magic methods such as __iter__ and __len__
-# * no inheritance
-# * doesn't work with existing help() function
+# * need setter methods to update attributes
+# * inheritance is not supported
+# * slower calls to special methods
+# * there is no "self"
+# * limited support for help()
import sys
-class Object(object):
+class Object:
'Holder for anything you want to attach to it'
+# The Python interpreter looks for special methods in the class dictionary
+# Add support for them by dispatching them back to the instance methods
+for sm in '''__len__ __bool__ __repr__ __str__ __iter__ __next__
+ __getitem__ __setitem__ __delitem__ __contains__
+ __eq__ __ne__ __lt__ __le__ __gt__ __ge__ __hash__
+ __add__ __mul__ __sub__ __truediv__ __floordiv__ __mod__
+ __pow__ __and__ __or__ __xor__ __invert__ __pos__ __neg__
+ __int__ __index__ __format__ __sizeof__
+ __call__ __enter__ __exit__ __reduce__ '''.split():
+ setattr(Object, sm, lambda self, *args, sm=sm: self.__dict__[sm](*args))
+
def classify(local_dict=None):
+ 'Move local definitions to an instance dictionary'
o = Object()
if local_dict is None:
local_dict = sys._getframe(1).f_locals
@@ -25,8 +38,8 @@
return o
-########################################################################
-### Simple example ###################################################
+############################################################################
+### Simple example #######################################################
def Animal(name):
'Animal-like class'
@@ -35,16 +48,20 @@
def set_name(newname):
nonlocal name
name = newname
+ def __getitem__(key):
+ return '%s is %sing' % (name, key.title())
return classify()
d = Animal('Fido')
d.speak()
d.set_name('Max')
d.speak()
+print(d.name)
+print(d['fetch'])
-########################################################################
-### Practical example ################################################
+############################################################################
+### Practical example ####################################################
def PriorityQueue(initial_tasklist):
'Retrieve tasks by priority. Tasks can be removed or reprioritized.'
@@ -67,7 +84,7 @@
def remove(task):
'Mark an existing task as REMOVED. Raise KeyError if not found.'
- entry = entry_finder.pop(task)
+ entry = entry_pop(task)
entry[-1] = REMOVED
def pop():
@@ -79,26 +96,47 @@
return task
raise KeyError('pop from an empty priority queue')
- def tasklist():
+ def __iter__():
'Show task in order of priority'
pq.sort()
- return [task for priority, count, task in pq if task is not REMOVED]
+ for priority, count, task in pq:
+ if task is not REMOVED:
+ yield task
+
+ def __repr__():
+ return 'PriorityQueue()'
+
+ def __str__():
+ return 'PriorityQueue with %d pending tasks' % __len__()
+
+ # Some work can delegated to another object
+ __contains__ = entry_finder.__contains__
+ __len__ = entry_finder.__len__
+ entry_pop = entry_finder.pop
for task, priority in initial_tasklist:
add(task, priority)
return classify()
-# note: the following calls are the same as would be used
-# if the priority queue were defined as a regular class
-todo = PriorityQueue([('fish', 5), ('play', 3)])
-todo.add('code', 1)
-todo.add('sleep', 6)
-print(todo.tasklist())
-print('Pop the topmost task: %r' % todo.pop())
-print("Deprioritize 'play'")
-todo.add('play', 10)
-todo.remove('sleep')
-print(todo.tasklist())
-help(PriorityQueue)
-help(todo.add)
+
+if __name__ == '__main__':
+
+ # Note: Client code is written normally. It makes no difference
+ # whether a PriorityQueue was implemented as a regular class or
+ # implemented using closures.
+
+ todo = PriorityQueue([('fish', 5), ('play', 3)])
+ todo.add('code', 1)
+ todo.add('sleep', 6)
+ print(list(todo))
+ print('Pop the topmost task: %r' % todo.pop())
+ print("Deprioritize 'play'")
+ todo.add('play', 10)
+ todo.remove('sleep')
+ print(len(todo))
+ print(list(todo))
+ print(todo)
+ print('fish' in todo)
+ help(PriorityQueue)
+ help(todo.add)