2

I have the following code. What would be the best way to evaluate the command variable and the parameters it contains.

This is a contrived example, but the easiest way to explain what I am trying to do on a bigger scale.

class Job():
  def random_number(self, start, end, prec=0):
    number = round(random.uniform(start,end),prec)
    if(prec == 0):
      return int(number)
    return number

  def run(self, command):
    #command = "self.random_number(1,10,0)"
    #**************
    # What would be the best way to 'eval' the content of the 'command' variable and the parameters it contains?
    #**************

job = Job()
job.run("self.random_number(1,10,0)")

2 Answers 2

5

Generally, this seems a bad idea, consider restructuring your code. That said, you may make use of getattr(...) in combination with splitting your string into a function and a params part:

import random, re

class Job():
    def random_number(self, start, end, prec=0):
        number = round(random.uniform(start, end), prec)
        if (prec == 0):
            return int(number)
        return number

    def run(self, command):
        fun, params, _ = re.split(r'[()]', command)
        params = map(int, params.split(","))

        func = getattr(Job, fun)
        print(func(*params))

job = Job()
job.run("random_number(1,10,0)")

Obviously, you'd need to add some error management (broken strings, functions, that don't exist, floats instead of integers - you get the idea).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it was that regex that I was looking for. That will help me out a lot, and I am actively working on redesigning the code, but I just need this to get over an initial hurdle.
0

You can use the eval() function like so:

 def run(self, command):
    return eval(command)

would this work for you?

4 Comments

No I get an error, saying that random_number is not a member of the Job Object
What @Bhavye Mathur said works for me, no error. But the security of the eval could the potential problem
@kaktus_car Thanks for the warning, always better to be safe than sorry, so I do a check of the commands first before I run them.
@PrestonDocks You're welcome, I agree, especially if you are evaluating user inputs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.