blob: ec895b7e07e886504030f6293e6111b521117dcd [file] [log] [blame]
Guido van Rossumc6360141990-10-13 19:23:40 +00001# 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#
25def dumpsymtab(dict):
26 for key in dict.keys():
27 dumpvar(key, dict[key])
28
29# Dump a single variable
30#
31def dumpvar(name, x):
32 import sys
33 t = type(x)
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000034 if t == type({}):
Guido van Rossumc6360141990-10-13 19:23:40 +000035 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`
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000045 elif t == type(sys):
Guido van Rossumc6360141990-10-13 19:23:40 +000046 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#
52def 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
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000061 if x == {}:
Guido van Rossumc6360141990-10-13 19:23:40 +000062 return 1
63 return 0