Make 'def' and 'class' usable within expressions
Shane Hathaway
shane at zope.com
Wed Mar 24 16:58:10 EST 2004
In thinking about PEP 318, I came across an idea that might be worth
pursuing further. It goes deeper than PEP 318, so it would need its own
PEP.
The idea is to make 'def' and 'class' usable within expressions.
Expressions using 'def' or 'class' are followed by a code block. Upon
evaluation of the expression, the 'def' or 'class' symbol evaluates as the
function or class created by the code block. Only one 'def' or 'class' is
allowed per expression.
Some examples follow.
# Define a staticmethod named 'now'.
class datetime:
now = staticmethod(def):
ticks = time.time()
return datetime(ticks)
# Increment a counter, under control of a lock.
def increment():
self.increment_lock.synchronize(def):
self.counter += 1
# Define an interface.
ICustomer = Interface(class):
def get_id():
"""Return the customer ID"""
# Create a singleton object that ignores what you write to it.
dev_null = singleton(class):
def write(self, data):
pass
When an expression uses 'def', the subsequent code block becomes a
function and therefore does not execute unless called by the expression.
When an expression uses 'class', the subsequent code block becomes a class
object and therefore executes before being passed to the expression.
Do you like or dislike it? Why?
Shane
More information about the Python-list
mailing list