|
5
|
1 # Module 'dump'
|
|
|
2 #
|
|
|
3 # Print python code that reconstructs a variable.
|
|
|
4 # This only works in certain cases.
|
|
|
5 #
|
|
|
6 # It works fine for:
|
|
|
7 # - ints and floats (except NaNs and other weird things)
|
|
|
8 # - strings
|
|
|
9 # - compounds and lists, provided it works for all their elements
|
|
|
10 # - imported modules, provided their name is the module name
|
|
|
11 #
|
|
|
12 # It works for top-level dictionaries but not for dictionaries
|
|
|
13 # contained in other objects (could be made to work with some hassle
|
|
|
14 # though).
|
|
|
15 #
|
|
|
16 # It does not work for functions (all sorts), classes, class objects,
|
|
|
17 # windows, files etc.
|
|
|
18 #
|
|
|
19 # Finally, objects referenced by more than one name or contained in more
|
|
|
20 # than one other object lose their sharing property (this is bad for
|
|
|
21 # strings used as exception identifiers, for instance).
|
|
|
22
|
|
|
23 # Dump a whole symbol table
|
|
|
24 #
|
|
|
25 def dumpsymtab(dict):
|
|
|
26 for key in dict.keys():
|
|
|
27 dumpvar(key, dict[key])
|
|
|
28
|
|
|
29 # Dump a single variable
|
|
|
30 #
|
|
|
31 def dumpvar(name, x):
|
|
|
32 import sys
|
|
|
33 t = type(x)
|
|
559
|
34 if t == type({}):
|
|
5
|
35 print name, '= {}'
|
|
|
36 for key in x.keys():
|
|
|
37 item = x[key]
|
|
|
38 if not printable(item):
|
|
|
39 print '#',
|
|
|
40 print name, '[', `key`, '] =', `item`
|
|
|
41 elif t in (type(''), type(0), type(0.0), type([]), type(())):
|
|
|
42 if not printable(x):
|
|
|
43 print '#',
|
|
|
44 print name, '=', `x`
|
|
559
|
45 elif t == type(sys):
|
|
5
|
46 print 'import', name, '#', x
|
|
|
47 else:
|
|
|
48 print '#', name, '=', x
|
|
|
49
|
|
|
50 # check if a value is printable in a way that can be read back with input()
|
|
|
51 #
|
|
|
52 def printable(x):
|
|
|
53 t = type(x)
|
|
|
54 if t in (type(''), type(0), type(0.0)):
|
|
|
55 return 1
|
|
|
56 if t in (type([]), type(())):
|
|
|
57 for item in x:
|
|
|
58 if not printable(item):
|
|
|
59 return 0
|
|
|
60 return 1
|
|
559
|
61 if x == {}:
|
|
5
|
62 return 1
|
|
|
63 return 0
|