1

Is there such a thing in python as an 'execute' statement that I can use similarly to the way I have below?

statement='print "hello world"'

def loop(statement):
    for i in range(100):
        for j in range(100):
            execute statement

loop(statement)
ThiefMaster
  • 298,938
  • 77
  • 579
  • 623
fergusdawson
  • 1,555
  • 3
  • 16
  • 19

1 Answers1

10

Yes, simply pass a callable and use statement() to execute it.

A callable is a function, lambda expression or any other object that implements __call__.

def loop(func):
    for i in range(100):
        for j in range(100):
            func()

def say_hello():
    print "hello world"
loop(say_hello)

If you really want to execute code from a string (trust me, you don't!), there is exec:

>>> code = 'print "hello bad code"'
>>> exec code
hello bad code
ThiefMaster
  • 298,938
  • 77
  • 579
  • 623