Data Representation?
Peter Otten
__peter__ at web.de
Sun Oct 12 05:21:06 EDT 2003
Kris Caselden wrote:
> Say I have some data:
>
>>>> a=[1]
>>>> b=[2]
>>>> link=[a,b]
>
> The simplest why to write this to a file represents it as
>
>>>> print str(link)
> [[1], [2]]
>
> Unfortunately, if this is read back in via execfile(), the whole
> dynamic nature of changing 'link' by changing 'a' and 'b' is lost. Is
> there any way to write data so that the list name is written instead
> of the list's values? Essentially, '[[a], [b]]' instead of '[[1],
> [2]]'? Any help most appreciated.
I'm not sure what you mean by [[a], [b]]. If it is sufficcient that
link[0] is a and link[1] is b
i. e. they refer to the same list when restored, I suggest that you
introduce a namespace class and make a, b and link attributes. You can then
use the standard pickle procedure:
import pickle
class Namespace:
def __str__(self):
return str(self.__dict__)
ns = Namespace()
ns.a = [1]
ns.b = [2]
ns.link = [ns.a, ns.b]
pickle.dump(ns, file("tmp", "w"))
ns2 = pickle.load(file("tmp", "r"))
assert ns2.a is ns2.link[0]
assert ns2.b is ns2.link[1]
print ns2
ns2.b.append(3)
print ns2
Peter
More information about the Python-list
mailing list