"Extracting" a dictionary

D

Daniel Klein

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
 
L

Leif K-Brooks

Daniel said:
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.
42
 
H

Heiko Wundram

Am Montag, 17. Mai 2004 21:34 schrieb Leif K-Brooks:
From the documentation:

"""
locals()

Update and return a dictionary representing the current local symbol table.
Warning: The contents of this dictionary should not be modified; changes may
not affect the values of local variables used by the interpreter.
"""

Heiko.
 
X

xtian

Daniel Klein said:
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

The most straightforward way I know is
23 42

This only works with globals, though - there's a corresponding
locals(), but unfortunately the docs say updating it's a no-no - the
dict returned could be a copy of the real locals dict (or the real
locals might not be in a dict at all). The interpreter is free to
ignore changes to the dictionary that locals() returns (although it
happens not to in CPython at the moment, that's an implementation
detail).

Even with the globals, it's a bit magical and could end up overwriting
names that match a key in the dictionary (it would be irritating if
one of the keys was "file" or "list").

Maybe a cleaner way to do essentially what you want is to use the
martellibot's Bunch recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308

This would allow you to do:
def __init__(self, **kwds):
self.__dict__.update(kwds)

23 42

This means you're not clobbering the global or local namespace with
arbitrary bindings, and you could have lots of Bunch instances for
different collections of bindings.

Cheers,
xtian
 
J

Jason Mobarak

Daniel said:
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

Is this illegal?
.... setattr(__main__, k, v)
....('oof', 'rab', 'zab')
 
L

Leif K-Brooks

Jason said:
Is this illegal?

... setattr(__main__, k, v)
...
('oof', 'rab', 'zab')

No, but it will need to be changed for the module's name, and won't work
at all in a local namespace (like a function).
 
L

Leif K-Brooks

Heiko said:
Am Montag, 17. Mai 2004 21:34 schrieb Leif K-Brooks:


From the documentation:

"""
locals()

Update and return a dictionary representing the current local symbol table.
Warning: The contents of this dictionary should not be modified; changes may
not affect the values of local variables used by the interpreter.
"""

Thanks for pointing that out, I was a bit lazy with TFM. Please ignore
my advice.
 
A

Arnold Filip

Daniel said:
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
 
P

Peter Hansen

Jason said:
Is this illegal?

... setattr(__main__, k, v)
...
('oof', 'rab', 'zab')

It executes, apparently, so why would you think it was "illegal"?

Note, however, that attempts to create variables programmatically
like this are almost always ill-conceived. If you don't know the
name of the variable in the first place, how are you planning to
access it later? And, as someone already said, it's probably better
just to continue to access things in the dictionary. More readable
probably.

-Peter
 
J

Jason Mobarak

Arnold said:
Daniel said:
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. At least with manipulating __main__ your not also
bringing in the possibility of excuting arbitrary code.
.... exec "%s = %d" % item
....
executed a system command(23, 42)

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.
 
A

Arnold Filip

Jason said:
Arnold said:
Daniel said:
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.

... exec "%s = %d" % item
...
executed a system command
(23, 42)
Concerning the security issue, the system call in your example can be
easily prevented:
.... 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
 
N

Noldoaran

Arnold Filip:
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

you could extract them in to there own namespace:.... def __init__(self, d):
.... self.__d = d
.... def __getattr__(self,attr):
.... return self.__d[attr]
.... def __setattr__(self,attr,value):
.... self.__d[attr] = value
.... def __delattr__(self,attr):
.... del self.__d[attr]
....Traceback (most recent call last):
File "<input>", line 1, in ?
File "<input>", line 3, in __init__
File "<input>", line 10, in __setattr__
(snip)
RuntimeError: maximum recursion depth exceeded
That didn't work like I hoped. I decided to share it anyway in case
someone can get it to work.

--Noldoaran
 
P

Peter Otten

Noldoaran said:
Arnold Filip:
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

you could extract them in to there own namespace:... def __init__(self, d):
... self.__d = d
... def __getattr__(self,attr):
... return self.__d[attr]
... def __setattr__(self,attr,value):
... self.__d[attr] = value
... def __delattr__(self,attr):
... del self.__d[attr]
...Traceback (most recent call last):
File "<input>", line 1, in ?
File "<input>", line 3, in __init__
File "<input>", line 10, in __setattr__
(snip)
RuntimeError: maximum recursion depth exceeded
That didn't work like I hoped. I decided to share it anyway in case
someone can get it to work.

Saying self.__d = dont_care invokes __setattr__() to set __d, __setattr__()
asks __getattr__() for __d, which asks __getattr__() for __d to determine
__d ...ad infinitum.
To avoid the recursion you must bypass __setattr__() by accessing __dict__
directly (and do some name mangling due to the evil double-underscore
attribute name by hand):
.... def __init__(self, d):
.... self.__dict__["_AttrDict__d"] = d
.... def __getattr__(self, attr):
.... return self.__d[attr]
.... def __setattr__(self, attr, value):
.... self.__d[attr] = value
.... def __delattr__(self, attr):
.... del self.__d[attr]
....Traceback (most recent call last):
File "<stdin>", line 1, in ?
Traceback (most recent call last):
File "<stdin>", line 1, in ?

While this works, you can achieve the same functionality in a more elegant
way:
.... def __init__(self, d):
.... self.__dict__.update(d)
....
A standard trick, by the way. Can't think of the right google keywords right
now, so I use another standard trick and leave finding them as an excercise
to the reader :)

Peter
 
N

Noldoaran

Peter Otten:
Saying self.__d = dont_care invokes __setattr__() to set __d, __setattr__()
asks __getattr__() for __d, which asks __getattr__() for __d to determine
__d ...ad infinitum.
To avoid the recursion you must bypass __setattr__() by accessing __dict__
directly.
(snip)

While this works, you can achieve the same functionality in a more elegant
way:

... def __init__(self, d):
... self.__dict__.update(d)
... (snip)
A standard trick, by the way. Can't think of the right google keywords right
now, so I use another standard trick and leave finding them as an excercise
to the reader :)

Peter

Thanks, Peter. I found another way that also works:
.... __getattr__ = dict.__getitem__
.... __getattribute__ = __getattr__
.... __setattr__ = dict.__setitem__
.... __delattr__ = dict.__delitem__
.... {'spam': 123, 'foo': 23, 'bar': 42}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top