From a2afdde360efeb3c0e13985c5c25eccb55dca2cc Mon Sep 17 00:00:00 2001 From: Jimmy Lai Date: Fri, 17 Jan 2020 10:25:42 -0800 Subject: [PATCH] add SimpleString.evaluated_value --- libcst/_nodes/expression.py | 8 ++++++++ libcst/helpers/tests/test_expression.py | 9 +++++++++ 2 files changed, 17 insertions(+) diff --git a/libcst/_nodes/expression.py b/libcst/_nodes/expression.py index 4d38ba15..47f22f3d 100644 --- a/libcst/_nodes/expression.py +++ b/libcst/_nodes/expression.py @@ -7,6 +7,7 @@ import re from abc import ABC, abstractmethod +from ast import literal_eval from contextlib import contextmanager from dataclasses import dataclass, field from enum import Enum, auto @@ -675,6 +676,13 @@ class SimpleString(_BasePrefixedString): with self._parenthesize(state): state.add_token(self.value) + @property + def evaluated_value(self) -> str: + """ + Return an :func:`ast.literal_eval` evaluated str of :py:attr:`value`. + """ + return literal_eval(self.value) + class BaseFormattedStringContent(CSTNode, ABC): """ diff --git a/libcst/helpers/tests/test_expression.py b/libcst/helpers/tests/test_expression.py index 915b99ea..625a1fd7 100644 --- a/libcst/helpers/tests/test_expression.py +++ b/libcst/helpers/tests/test_expression.py @@ -4,6 +4,7 @@ # LICENSE file in the root directory of this source tree. # # pyre-strict +from ast import literal_eval from typing import Optional, Union import libcst as cst @@ -28,3 +29,11 @@ class ExpressionTest(UnitTest): self, input: Union[str, cst.CSTNode], output: Optional[str], ) -> None: self.assertEqual(get_full_name_for_node(input), output) + + def test_simplestring_evaluated_value(self) -> None: + raw_string = '"a string."' + node = cst.helpers.ensure_type( + cst.parse_expression(raw_string), cst.SimpleString + ) + self.assertEqual(node.value, raw_string) + self.assertEqual(node.evaluated_value, literal_eval(raw_string))