Make 'def' and 'class' usable within expressions

Shane Hathaway shane at zope.com
Thu Mar 25 15:41:29 CET 2004


Ahem, I was hoping for opinions on this idea, either positive or 
negative.  It could make Python better or worse.  I need to know whether 
I should flesh out the proposal more.

I've added some comparisons below.  IMHO this syntax is clearer than the 
syntax proposed for PEP 318, and a little more powerful.

Shane Hathaway wrote:
> 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)

Today, this would be written as:

     class datetime:
         def now():
             ticks = time.time()
             return datetime(ticks)
         now = staticmethod(now)


>     # Increment a counter, under control of a lock.
> 
>     def increment():
>         self.increment_lock.synchronize(def):
>             self.counter += 1

Today, this would be written as:

     def increment():
         self.increment_lock.acquire()
         try:
             self.counter += 1
         finally:
             self.increment_lock.release()


>     # Define an interface.
> 
>     ICustomer = Interface(class):
>         def get_id():
>             """Return the customer ID"""

Today, this would be written as:

     class ICustomer:
         def get_id():
             """Return the customer ID"""
     ICustomer = Interface(ICustomer)


>     # Create a singleton object that ignores what you write to it.
> 
>     dev_null = singleton(class):
>         def write(self, data):
>             pass

     class dev_null:
         def write(self, data):
             pass
     dev_null = singleton(dev_null)

> 
> 
> 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