~divmod-dev/divmod.org/trunk

« back to all changes in this revision

Viewing changes to Epsilon/epsilon/unrepr.py

  • Committer: Jean-Paul Calderone
  • Date: 2014-06-29 20:33:04 UTC
  • mfrom: (2749.1.1 remove-epsilon-1325289)
  • Revision ID: exarkun@twistedmatrix.com-20140629203304-gdkmbwl1suei4m97
mergeĀ lp:~exarkun/divmod.org/remove-epsilon-1325289

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
import compiler
2
 
 
3
 
def unrepr(s):
4
 
    """
5
 
    Convert a string produced by python's repr() into the
6
 
    corresponding data structure, without calling eval().
7
 
    """
8
 
    return Builder().build(getObj(s))
9
 
 
10
 
def getObj(s):
11
 
    s="a="+s
12
 
    return compiler.parse(s).getChildren()[1].getChildren()[0].getChildren()[1]
13
 
 
14
 
class UnknownType(Exception):
15
 
    pass
16
 
 
17
 
class Builder:
18
 
 
19
 
    def build(self, o):
20
 
        m = getattr(self, 'build_'+o.__class__.__name__, None)
21
 
        if m is None:
22
 
            raise UnknownType(o.__class__.__name__)
23
 
        return m(o)
24
 
 
25
 
    def build_List(self, o):
26
 
        return map(self.build, o.getChildren())
27
 
 
28
 
    def build_Const(self, o):
29
 
        return o.value
30
 
 
31
 
    def build_Dict(self, o):
32
 
        d = {}
33
 
        i = iter(map(self.build, o.getChildren()))
34
 
        for el in i:
35
 
            d[el] = i.next()
36
 
        return d
37
 
 
38
 
    def build_Tuple(self, o):
39
 
        return tuple(self.build_List(o))
40
 
 
41
 
    def build_Name(self, o):
42
 
        if o.name == 'None':
43
 
            return None
44
 
        raise UnknownType('Name')
45
 
 
46
 
    def build_Add(self, o):
47
 
        real, imag = map(self.build_Const, o.getChildren())
48
 
        try:
49
 
            real = float(real)
50
 
        except TypeError:
51
 
            raise UnknownType('Add')
52
 
        if not isinstance(imag, complex) or imag.real != 0.0:
53
 
            raise UnknownType('Add')
54
 
        return real+imag