Python expression evaluator.

Answered

Is there any way I can evaluate an expression like this?

size = 5
str = "a" * size

The str variable holds aaaaa. Is there any API that could give me the value str holds?

I saw the PyAnyExpressionEvaluator class. Tried using the evaluate method. But that doesn't seem to return the result I'm expecting.

Could this be done before runtime?

4 comments
Comment actions Permalink

> But that doesn't seem to return the result I'm expecting.
Sorry, but it's impossible to help without seeing your code and understanding what your expectation is vs actual result.

0
Comment actions Permalink

Sorry for the inconvenience.

size = 5;
PyBinaryExpression expression = ("a" * size)-> holds the reference to this expreesion;
PyAnyExpressionEvaluator expressionEvaluator = new PyAnyExpressionEvaluator(true);
Object result = expressionEvaluator.evaluate(expression);

I'm excepting the result to hold aaaaa.

0
Comment actions Permalink

Hi Sanjay! 

Evaluating multiplying a string literal by a constant number could be supported in PyEvaluator, it's the right place for this logic, but as far as I see this case is indeed not yet covered. Most of the supported cases were added on-demand, though, so feel free to submit a PR implementing it to PyCharm Community. Alternatively, you can always replicate the necessary parts of PyEvaluator#evaluateBinary logic in your plugin. On the whole, I'm not aware of a place in our codebase where it's already done, we can only infer the return types of such expressions, not deduce string values themselves.

0
Comment actions Permalink

Thank you for your reply. I will try to replicate the logic myself then.

0

Please sign in to leave a comment.