Implementation of the global statement

Michael Hudson mwh at python.net
Fri Nov 29 07:11:46 EST 2002


"Terry Reedy" <tjreedy at udel.edu> writes:

> "Bengt Richter" <bokr at oz.net> wrote in message
> news:as5ugi$a48$0 at 216.39.172.122...
> >  >>> def foo(x): print x
> >  ...
> >  >>> bar = foo.__get__('Hi via foo')
> >  >>> bar()
> >  Hi via foo
> 
> This is a new one for me:
> 
> >>> def f(): pass
> ...
> >>> f.__get__
> <method-wrapper object at 0x015197B0>
> >>> f.__get__.__doc__
> 'descr.__get__(obj[, type]) -> value'
> 
> Seems to be a new, undocumented (?, not in indexes) method producing a
> new, undocumented (?) internal type.  Not something to bank a product
> on ;-)

Curiouser and curiouser:

>>> def f(arg):
...  print arg
... 
>>> f.__get__("e")  
<bound method ?.f of 'e'>
>>> f.__get__("e")()
e
>>> def g(a,b):
...  print a, b
... 
>>> g.__get__("f")("e")
f e
>>> g.__get__("f","e")     
<bound method ?.g of 'f'>
>>> g.__get__("f","e")()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: g() takes exactly 2 arguments (1 given)
>>> g.__get__("f","e")("d")
f d

Boggle :)

Actually, I think I have some faint idea what is going on here: When
you go

    instance.attr

the translates, roughly, so long as 'attr' isn't a key in the
instance's __dict__, into

    instance.__class__.__dict__['attr'].__get__(instance)

so if 

    instance.__class__.__dict__['attr']

is a regular function, the behaviour above is what produces the bound
method.

Hmm, actually, the translation might be:

  instance.__class__.__dict__['attr'].__get__(instance, instance.__class__)

That whirring sound you can hear is my brain on its spin cycle :)

Cheers,
M.

-- 
  The "of course, while I have no problem with this at all, it's
  surely too much for a lesser being" flavor of argument always
  rings hollow to me.                       -- Tim Peters, 29 Apr 1998



More information about the Python-list mailing list