Implementation of the global statement
Bengt Richter
bokr at oz.net
Thu Nov 28 15:32:18 EST 2002
On Thu, 28 Nov 2002 17:41:23 +1300, Greg Ewing <see_reply_address at something.invalid> wrote:
>Mikael Olofsson wrote:
>
>> Is there an obvous way to have f (still defined in A) manipulate
>> objects in B when executed in B?
>
>
>Don't know whether it counts as "obvious", but I
>think there is a way (short of using exec):
>
> import new
> g = new.function(f.func_code, B.__dict__)
>
>This creates a new function g which has the
>same code as f but a different global namespace.
>
>(You can't just change f.func_globals directly
>because it's a read-only attribute, unfortunately.)
>
This kind of stuff raises questions in my mind as to what
will be guaranteed to work forever and what may be quasi-experimental,
or depend on things that really shouldn't be locked in to become
a millstone of backwards-compatibility to inhibit Guido's freedom.
E.g., I noticed recently that you can (2.2.2) take an ordinary function and
create an instant apparent bound method of an arbitrary object:
>>> def foo(x): print x
...
>>> bar = foo.__get__('Hi via foo')
>>> bar()
Hi via foo
>>> bar
<bound method ?.foo of 'Hi via foo'>
>>> baz = foo.__get__(123)
>>> baz()
123
>>> baz
<bound method ?.foo of 123>
>>> baz(456)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: foo() takes exactly 1 argument (2 given)
You could use this as an alternative to the default-argument hack, but how
locked in is this feature? What should be the advice for/against using it
vs e.g. a plain vanilla class with a __call__ method and a place to hold the state?
BTW, IIRC you can also build a property "by hand" using __get__, but how in/advisable is that?
ISTM pretty soon we are going to need a separate book on __Python__ the meta-language ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list