sublimehq / sublime_text

Issue tracker for Sublime Text
https://www.sublimetext.com
813 stars 40 forks source link

Arithmetic command failed evaluate "math.*" in multi-lines #3606

Open cheelam opened 4 years ago

cheelam commented 4 years ago

Description

Arithmetic command able to work on "math" methods (e.g. math.sqrt(4)) in single-line selection, but not in multi-line selection.

Steps to reproduce

Create a new tab, paste the following code in it: 1+2 int(3.4) float(5) str(6+7) math.sqrt(9)

  1. Ctrl+A to select all
  2. Ctrl+Shift+L to split into lines
  3. Ctrl+Shift+P to bring up the Command Palette
  4. Type, "arithmetic" and Enter and Enter again

Texts will be replaced into: 3 3 5.0 13 0

Expected behavior

Expected output is: 3 3 5.0 13 3.0

Actual behavior

def try_eval(str):
    try:
        # Original: return eval(str, {}, {})
        return eval(str, {'math': math}, {})                      <- fix
    except Exception as e:
        print(e)
        return None

Environment

BenjaminSchaaf commented 4 years ago

While the arithmetic command does let you evaluate some basic python it's not meant for arbitrarily evaluating your python in-place. There might be a case for making an exception for math, though there's plenty of other modules that could be useful (like statistics) and including all of them wouldn't be great. If you want to use function in math for now you can use __import__('math').sqrt.

cheelam commented 4 years ago

Thanks. This "import" is very helpful.