Rather than decorators, how about sections?

Mark Bottjer mark_bottjer at hotmail.com
Thu Aug 12 04:01:05 CEST 2004


Stefan Eischet wrote:
> On 11.08.2004, at 20:55, Christophe Cavalaria wrote:
>> Paul Morrow wrote:
>> - It'll break code that binds arbitrary functions as a member 
>> function. You can't do things like that anymore :
>>
>>>>> def f(s):
>>>>>     print "Hi, I'm function f"
>>>>> class Klass:
>>>>>     doIt = f
>>>>> Klass().doIt()
[snip]
> How would you solve this problem with decorators, btw?
> class Klass:
>     @stuff
>     doIt = f

I would expect it to be more like:

@stuff
def f(s):
   pass
class Klass:
   doIt = f

@stuff modifies f, so it would precede it. The assignment inside Klass 
is just that, a simple assignment; whatever f is, Klass.doIt now refers 
to it was well.

> If there was a rule that assigned functions in the class body (doIt=f) 
> default to normal methods whatever their first arg is called, would that 
> be okay? After all, that is how it works right now.

That's certainly true of def statements inside classes, but doIt is just 
an assignment. If I understand correctly, you're proposing that the 
compiler do something special if a variable at class scope is being 
assigned a known function value. I'm not sure the compiler can know that:

@stuff
def f(s):
   pass
g = f
def id(a):
   return a
class Klass:
   doIt = g
   doItAgain = id(a)

How is the compiler going to sort all this out at compile time?

Also, such implicit typing would prevent one from storing non-methods. 
Raw functions can be useful even inside classes:

class Frob:
   def __init__(self,frob):
     self.__frob = frob
   def __call__(self,buf):
     return self.__frob(buf)
Frob(frob.frobnicate)('This is a test.')
Frob(frob.frobulate)('This is another test.')
Frob(frob.frobnosticate)('The best test of all!')

   -- Mark



More information about the Python-list mailing list