Metaprogramming Example

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Apr 18 04:48:14 EDT 2008


andrew cooke a écrit :
> bruno:
>> Ho, and yes : one day, you'll get why it's such a good thing to unite
>> functions and methods !-)
> 
> me:
>> PS Is there anywhere that explains why Decorators (in the context of
>> functions/methods) are so good?  I've read lots of things saying they
>> are good, but no real justification of why.
> 
> in the text above i wrote "Decorators" rather than "Descriptors".  it
> was in response to bruno's comment, also above.  sorry for the
> confusion.

Ho, you meant Descriptors ?

Well, a first point is that the support for methods is built on a 
combination of two "general purpose" constructs - callable objects and 
the descriptor protocol - instead of being a special-case construct by 
itself. IOW, this is build *with* Python itself, instead of being built 
*into* Python.

Practically, this means that (amongst other niceties) :
- you can define functions outside classes and use them as instance or 
class methods
- you can add/replaces methods dynamically on a per-class or 
per-instance basis
- you can access the function object of a method and use it as a function
- you can define your own callable types, that - if you implement the 
appropriate support for the descriptor protocol - will be usable as 
methods too


> also, sorry for the inflammatory language

Which one ???

> by referring to the titanic
> i didn't mean that python was a disaster, rather that the "iceberg" is
> still there (i am not 100% sure what the iceberg is, but it's
> something
> to do with making namespaces explicit in some places and not others).

I guess you're thinking of the self argument, declared in the function's 
signature but not "explicitly passed" when calling the method ?

If so, the fact is you *do* pass it explicitly - by calling the function 
*as a method of an objet*. Given the following definitions:

   def func(obj, data):
     print "obj : %s - data : %s" % (obj, data)

   class Foo(object):
     meth = func

   f = Foo()

What the difference between:

   func(f, 42)

and

   f.meth(42)

In both cases, f is directly and explicitly involved as one of the 
"targets" of the call.

My 2 cents...



More information about the Python-list mailing list