Strange behavior of __get__ in a descriptor in IPython

Fernando Perez fperez.net at gmail.com
Wed Nov 7 19:16:00 CET 2007


Jakub Hegenbart wrote:

> Hi,
> 
> I'm studying the descriptor protocol and its usage from the following
> document:
> 
> http://users.rcn.com/python/download/Descriptor.htm
> 
> There is some sample code:
> 
> http://users.rcn.com/python/download/Descriptor.htm#descriptor-example
> 
> that behaves in a different way on my machine than the example suggests:
> 
> In [2]: a=MyClass()
> 
> In [3]: a.x
> Retrieving var "x"
> Retrieving var "x"
> Out[3]: 1
> 
> On the other hand, in the 'plain' Python shell, it's invoked only once as
> expected:
> 
>>>> a=desc.MyClass()
>>>> a.x
> Retrieving var "x"
> 10
>>>>
> 
> Should I take as granted that IPython might in some cases access an
> attribute
> of an object more than once even in face of side effects, or is this a bug?

Yup, IPython does access attributes more than once in an attempt to determine
if things can be called as functions.  This behavior, however, only exists
if 'autocall' is active.  Here's an example:

In [1]: run desc

In [2]: m.x
Retrieving var "x"
Retrieving var "x"
Out[2]: 10

In [3]: m.x
Retrieving var "x"
Retrieving var "x"
Out[3]: 10

In [4]: autocall 0
Automatic calling is: OFF

In [5]: m.x
Retrieving var "x"
Out[5]: 10


As you can see, once autocall is disabled, the double access goes away.  There
really is no way to provide the autocall feature without any side effects
whatsoever, so if you need to avoid them at all costs, disable this feature. 
You can do it permanently by editing your ipythonrc file.

Cheers,

f




More information about the Python-list mailing list