determining context of getattr

Thomas Wouters thomas at xs4all.net
Mon Aug 21 04:13:52 EDT 2000


On Mon, Aug 21, 2000 at 12:53:10AM -0400, Tripp Lilley wrote:

> Is there any way to know inside of a getattr call whether or not the
> returned object will be immediately subjected to a __call__ invocation?

> ie: if I do this:
> 
> 	foo.say( )

> can foo's __getattr__ know that whatever it returns for 'say' is going
> to immediately be __call__'ed?

Short answer: No. Long answer: No :) Very long answer: No, unless you use
bytecodehacks, and don't expect the code to work properly on anything but
the Python you wrote it on, and don't expect it to work in all situations,
and don't care about Pythonic code. So, in short, don't bother.

> Right now, I'm doing a very nasty, overhead-laden hack in which I have
> wrapper classes for all of the primitive types, that implement coercion,
> etc., so that the returned objects "act" like primitives when subjected
> to math, but "act" like methods when __call__'ed (ie: __call__ simply
> returns the "value" of the object).

That's the way to do it. It's not nasty, it's exactly how you should do it
;) In your examples of how you want to use it, what do you expect this to
do:

    x = foo.value
    print x
    print x + 9
    print x()

In 'normal' Python, this would work exactly the same. (In fact, this is the
same as what your example would do, except that 'x' wouldn't be a variable,
but an item on the stack.) Not to mention:

    print (foo.value + 9)()

> I vaguely recall hearing something about Py3k making primitive types
> into real, first-class objects that I might subclass to effect this
> behaviour. Any truth to that recollection of mine? ie:
> 
> 	class TrippInt (int):
> 		def __call__ (self):
> 			return self.__value__

Yes, that's high on the wishlist of Py3K, though syntax may vary.

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list