[Python-Dev] Callable, non-descriptor class attributes.

Guido van Rossum guido at python.org
Sat Mar 12 01:10:36 CET 2011


On Fri, Mar 11, 2011 at 6:49 PM, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Thomas Wouters wrote:
>
>>  2. Make CFunctions turn into methods in CPython (after a period of
>> warning about the impending change, obviously.) The actual *usecase* for
>> this is hard to envision
>
> While not necessary for the case being discussed here, this would
> be a big help for Pyrex and Cython, where currently some awkward
> things have to be done to get a Python class with methods implemented
> in C.

I appreciate the use case, but I believe the right solution there is
to create a custom decorator implementing the desired descriptor
behavior. There simply are too many places where existing code depends
on a built-in function placed in a class *not* turning into a method.

Also, there is a slippery-slope argument here: if we were to add such
a descriptor to CFunctions, why not to other callables? I think we
need to stick to the rule where only Python functions have a
method-making descriptor.

Off-line, I discussed the patch with Thomas and we ended up agreeing
that the warning should only be issued for CFunctions used as class
variables.

In summary, I don't think the problem is with the difference between
CFunctions and pure-Python functions. That difference is well-defined
and shouldn't go away. The problem is that it is fairly common that
something that is a CFunction in CPython is replaced by a pure-Python
function, either in another Python VM, or in a different environment
(think heapq.py vs. _heapq.c), or when some unittest uses dependency
injection (i.e. temporarily replaces a built-in with a wrapper written
in Python). Such substitutions are generally transparent, but not when
the function is used as a class attribute. We should do all these
things to address this:

- on the "consuming" side, wrap such class variables in staticmethod() calls

- on the "producing" side (e.g. in PyPy) wrap pure-Python functions
that are substitutes for CPython builtins in a custom descriptor that
prevents method-making

- in CPython, warn whenever a built-in function is used as a class variable

-- 
--Guido van Rossum (python.org/~guido)


More information about the Python-Dev mailing list