1

I want to be able to bring in a lambda function from a txt file, and have it be able to run as if it were a normal section of code.


chain = "What has to be broken up"

reduction = 'lambda chain: chain[0:8]'

x = exec(reduction)

print(x)      #only prints out 'None'

print(exec(x = reduction))    #causes error

print(exec(reduction)) #prints out 'None'

What I am hoping for the output to be is the first 8 characters of the string chain, 'What has'. How can I make this work to run the function?

Yarn Saw
  • 57
  • 1
  • 9

2 Answers2

2

To run a function, you have to use () after it.

To get the value of an expression in a string, you need to use eval(), not exec(). See What's the difference between eval, exec, and compile?.

Since your lambda function has a parameter, you need to give it an argument when calling it.

chain = "What has to be broken up"
reduction = 'lambda c: c[0:8]'
x = eval(reduction)(chain)
print(x)

If you don't want to give it an argument, you should take out the parameter. But you still need to provide an empty argument list.

chain = "What has to be broken up"
reduction = 'lambda: chain[0:8]'
x = eval(reduction)()
print(x)
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

I'm not sure if I understand what you're trying to do, but here's a guess. It uses eval instead of exec() since what's in reduction is an expression:

chain = "What has to be broken up"
reduction = 'lambda string: string[0:8]'
x = eval(reduction)(chain)
print(x)  # -> What has
martineau
  • 119,623
  • 25
  • 170
  • 301