"Extracting" a dictionary
Arnold Filip
afilip--usenet at freenet.de
Wed May 19 04:47:37 EDT 2004
Jason Mobarak wrote:
> Arnold Filip wrote:
>
>> Daniel Klein wrote:
>>
>>> Hello,
>>>
>>> I'm quite new to Python, and since a not-so-superficial look into the
>>> docs didn't answer my question (although it still feels quite basic),
>>> I decided to turn to this place:
>>>
>>> Is there a way to 'extract' a dictionary into the current namespace?
>>> That is, if you have
>>> {'foo' : 23, 'bar' : 42}
>>> you would get a variable foo with value 23 and a variable bar with
>>> value 42? Such a function would of course only work on string keys
>>> and would probably have to check that, but still, it sounds practical
>>> enough that surely someone else thought of it before.
>>>
>>> Daniel
>>>
>>
>> How about this:
>>
>> In [1]: d = {'foo' : 23, 'bar' : 42}
>>
>> In [2]: for item in d.items():
>> ...: exec "%s = %d" % item
>> ...:
>>
>> In [3]: foo
>> Out[3]: 23
>>
>> In [4]: bar
>> Out[4]: 42
>>
>
> That's disgusting.
I agree. But IMHO at least for a newbie that's the easiest way to do it.
No need to know anything about the "internals" of python.
> At least with manipulating __main__ your not also
> bringing in the possibility of excuting arbitrary code.
>
> >>> d = {'foo' : 23, '__import__("os").system("echo executed a system command"); bar' : 42}
> >>> for item in d.items():
> ... exec "%s = %d" % item
> ...
> executed a system command
> >>> foo,bar
> (23, 42)
Concerning the security issue, the system call in your example can be
easily prevented:
>>> d = {'foo' : 23, '__import__("os").system("echo executed a system
command"); bar' : 42}
>>> for i in d.items():
... exec "(%s) = %d" % i
...
Traceback (most recent call last):
File "<stdin>", line 2, in ?
File "<string>", line 1
(__import__("os").system("echo executed a system command"); bar) = 42
^
SyntaxError: invalid syntax
>
> Granted, the reasons for wanting to do this may be ill-concieved,
> there's probably a better, more obvious solution -- since doing the
> subject of this thread is neither easy nor elegant.
Totally agree.
Hey Daniel, may be you should point out _what_ you want to achieve
rather than _how_ you can do this and that.
Cheers,
Arnold
More information about the Python-list
mailing list