Make 'def' and 'class' usable within expressions

Shane Hathaway shane at
Wed Mar 24 22:58:10 CET 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 

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.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):

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?


More information about the Python-list mailing list