Puzzle: anonymous tuple unpacking w/o eval
Duncan Booth
duncan at NOSPAMrcp.co.uk
Fri May 16 10:20:10 EDT 2003
"Edward K. Ream" <edreamleo at charter.net> wrote in
news:vc9r28seqent63 at corp.supernews.com:
>> __import__(__name__).__dict__.update(dict(tuple))
>>
>> (or, perhaps,
>>
>> globals().update(dict(tuple))
>
> Spectacular!
>
> Is there a way to do something similar with locals() so as not to
> affect the global namespace? The documentation sternly warns against
> modifying locals().
No, but the obvious thing to do is to modify a class object which keeps
your extra names out of the global namespace:
>>> val1, val2, val3 = 1, 2, 3
>>> aList = (("a",val1),("b",val2),("c",val3))
>>> class C: pass
>>> c = C()
>>> c.__dict__.update(dict(aList))
>>> print c.a, c.b, c.c
1 2 3
> P.S. Your answer also answers another question I've had for a long
> time. If f is a function object, we can use inspect to get any kind
> of info about f. But how to get the function object for a function f
> within f itself? Now it's clear:
>
> globals().get("f")
>
> or anonymously:
>
> globals().get(sys._getframe(0).f_code.co_name)
>
> Many thanks for unlocking this door.
>
That only works if the function name is also the name of a global variable,
which is rarely true if you are uses classes and methods.
You could try this instead:
>>> class C:
def aMethod(self):
for o in gc.get_referrers(sys._getframe(0).f_code):
print o
>>> inst = C()
>>> inst.aMethod()
<frame object at 0x007D45A8>
<function aMethod at 0x00986440>
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list