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
  • 310,957
  • 84
  • 592
  • 636
fergusdawson
  • 1,645
  • 3
  • 17
  • 20

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
  • 310,957
  • 84
  • 592
  • 636