# Simple tool for making class-like objects using closures in Python 3
#
# Advantages:
# * cleaner coding style -- internal reference don't use "self.r"
# * faster internal references
# * faster external calls - no bound methods or rewriting arg tuples
# * attributes are automatically "private"
#
# Disadvantages:
# * no direct access to attributes
# * no inheritance
# * doesn't work with existing help() function
import sys
class Object(object):
'Holder for anything you want to attach to it'
def classify(local_dict=None):
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
return classify()
d = Animal('Fido')
d.speak()
d.set_name('Max')
d.speak()
########################################################################
### 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_finder.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 tasklist():
'Show task in order of priority'
pq.sort()
return [task for priority, count, task in pq if task is not REMOVED]
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)
Diff to Previous Revision
--- revision 4 2012-04-02 05:03:22
+++ revision 5 2012-04-02 07:05:38
@@ -7,7 +7,6 @@
# * attributes are automatically "private"
#
# Disadvantages:
-# * current version doesn't support magic methods
# * no direct access to attributes
# * no inheritance
# * doesn't work with existing help() function
@@ -16,7 +15,6 @@
class Object(object):
'Holder for anything you want to attach to it'
- pass
def classify(local_dict=None):
o = Object()
@@ -47,24 +45,24 @@
########################################################################
### Practical example ################################################
-import heapq
-import itertools
+def PriorityQueue(initial_tasklist):
+ 'Retrieve tasks by priority. Tasks can be removed or reprioritized.'
+ from heapq import heappush, heappop
-def priority_queue(initial_tasklist):
- 'Retrieve tasks by priority. Tasks can be removed or reprioritized.'
pq = [] # list of entries arranged in a heap
entry_finder = {} # mapping of tasks to entries
REMOVED = object() # placeholder for a removed task
- counter = itertools.count() # unique sequence count
+ 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)
- count = next(counter)
entry = [priority, count, task]
entry_finder[task] = entry
- heapq.heappush(pq, entry)
+ heappush(pq, entry)
+ count += 1
def remove(task):
'Mark an existing task as REMOVED. Raise KeyError if not found.'
@@ -74,16 +72,11 @@
def pop():
'Remove and return the lowest priority task. Raise KeyError if empty.'
while pq:
- priority, count, task = heapq.heappop(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 reprioritize(task, priority):
- 'Change a task priority. Raise KeyError if non found.'
- remove(task)
- add(task, priority)
def tasklist():
'Show task in order of priority'
@@ -95,17 +88,16 @@
return classify()
-# note: the following calls would be *exactly* the same
-# if the priority_queue had been defined as a regular class
-
-todo = priority_queue([('fish', 5), ('play', 3)])
+# 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.reprioritize('play', 10)
+todo.add('play', 10)
todo.remove('sleep')
print(todo.tasklist())
-help(priority_queue)
+help(PriorityQueue)
help(todo.add)