PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 30, 2022

[FIXED] How can I do an eval correctly in Python?

 October 30, 2022     eof, eval, python     No comments   

Issue

I'm trying to evaluate a string in a Flask project, but I keep getting this error.

File "<string>", line 0

    ^
SyntaxError: unexpected EOF while parsing

This is the code I am using

def f(x):
   input = "math.log((math.sin(x)**2) + 1) - (1 / 2)"
   string = input.replace("x",str(x))
   result = eval(string)
   return result

Solution

Because replace is a method of the string class, it must be called from the string itself.

def f(x):
   input = "math.log((math.sin(x)**2) + 1) - (1 / 2)"
   string = input.replace("x",str(x))
   result = eval(string)
   return result

But, you should avoid calling eval unless you absolutely have to; eval is evil. Eval (and its cousin exec) can open up your program to arbitrary code injections.

Can you explain your usecase a little more and I can see if I can suggest a better alternative?

Why wouldn’t this work:

def f(x):
    return math.log((math.sin(x)**2) + 1) - (1 / 2)


Answered By - Connor
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing