weird behavior wrapping global functions into classes

Alex Martelli aleaxit at yahoo.com
Thu Jun 14 15:21:14 EDT 2001


"Les Schaffer" <schaffer at optonline.net> wrote in message
news:ofohitsq7c4u4jitvoltev8pp5ctnvmule at 4ax.com...
> On Thu, 14 Jun 2001 16:19:26 +0200, "Alex Martelli" <aleaxit at yahoo.com>
> wrote:
>
> >Whenever a function is accessed as an attribute of a class or
>            ^
>            |___ python coded

Yes, an object of function type (as opposed to builtin-function-type,
or any other callable).

> >instance (and in the latter case, it's found in the class and
> >not in the instance itself), it's transmuted into a method
> >(unbound and bound, respectively).
>
> <steam release>
>   $$!!@(*!#(#!!@!@!!@
>   what the ?????!!!!!
>   sssssssssssssssssss....ssss......s....
> </steam release>
>
> how come the built-in open doesnt get transmuted but shelve.open does?
just
> because its not "python-coded"???

Because it's a different type.

D:\py21>python
Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
Alternative ReadLine 1.4 -- Copyright 2001, Chris Gonnerman
>>> type(open)
<type 'builtin_function_or_method'>
>>> import shelve
>>> type(shelve.open)
<type 'function'>

See?  shelve.open is of type 'function'.  __builtin__.open is of
type 'builtin_function_or_method'.  Only objects of type
'function' (i.e., functions in the proper sense, in Python terms)
are subject to the transformation.  All other kinds of callable
objects (including builtin_function_or_method's, instances
with a __call__ special method, classes, bound and unbound
methods, and other types you can code in extensions) aren't.

> your Callable thingy looks okay, but if its that easy, some such thing
> should be built right into Python so this issue is crystal clear and

I agree -- it should be.  But if I so propose, I'll be told "go write
a PEP".  Given it's about 5 lines of code, I'd feel silly if I had to
write 50 lines of PEP justifying it (and I've never seen a PEP as
short as just 50 lines:-), so I don't think I'll ever propose it.

> upfront/outfront. i never asked for dbopen to be a class method, or so i
> thought, yet i get hammered in an inconsistent way (built-in open: good,
> python-coded shelve.open: bad).

The rule is pretty consistent -- function, gets transformed, anything
else, doesn't.  Erroneously considering other callables 'functions' is a
very understandable confusion of course (I think the docs are guilty
of that too -- often they talk of 'a function' where actually they MEAN
'any callable').  The magic transformation, btw, does have its
usefulness -- that is how EVERY method of a Python instance or
class is treated, and it makes it easy to add methods to classes
outside of the class's body (not a frequent need, but...).


> anyway, .... thanks, alex....

You're welcome!


Alex






More information about the Python-list mailing list