1 # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2 # Licensed to PSF under a Contributor Agreement.
4 """Safely evaluate Python string literals without using eval()."""
8 simple_escapes
= {"a": "\a",
20 all
, tail
= m
.group(0, 1)
21 assert all
.startswith("\\")
22 esc
= simple_escapes
.get(tail
)
25 if tail
.startswith("x"):
28 raise ValueError("invalid hex string escape ('\\%s')" % tail
)
32 raise ValueError("invalid hex string escape ('\\%s')" % tail
)
37 raise ValueError("invalid octal string escape ('\\%s')" % tail
)
41 assert s
.startswith("'") or s
.startswith('"'), repr(s
[:1])
45 assert s
.endswith(q
), repr(s
[-len(q
):])
46 assert len(s
) >= 2*len(q
)
48 return re
.sub(r
"\\(\'|\"|
\\|
[abfnrtv
]|x
.{0,2}|
[0-7]{1,3})", escape, s)
59 if __name__ == "__main__
":