Converting a strng to an anonymous function

  • Thread starter Bruno Desthuilliers
  • Start date
B

Bruno Desthuilliers

Nathan Seese a écrit :
I'm writing a program to sort files with arbitrary python code. The
method I'm using for that is to pass sort an anonymous function taken
from the arguments. I'm wondering how to change a raw string into an
anonyous function.

Care to give a couple more explanation about your use case ? There might
be better solutions than eval/exec...
 
N

Nathan Seese

I'm writing a program to sort files with arbitrary python code. The
method I'm using for that is to pass sort an anonymous function taken
from the arguments. I'm wondering how to change a raw string into an
anonyous function.
 
B

bearophileHUGS

I'm writing a program to sort files with arbitrary python code. The
method I'm using for that is to pass sort an anonymous function taken
from the arguments. I'm wondering how to change a raw string into an
anonyous function.

Is this enough for you?
L = [1, -5, 7, -9]
sorted(L, key=abs) [1, -5, 7, -9]
func = "abs"
sorted(L, key=eval(func)) [1, -5, 7, -9]
func = "abs(x)"
sorted(L, key=lambda x: eval(func))
[1, -5, 7, -9]

Bye,
bearophile
 
N

Nathan Seese

I'm writing a program to sort files with arbitrary python code. The
method I'm using for that is to pass sort an anonymous function taken
from the arguments. I'm wondering how to change a raw string into an
anonyous function.

Is this enough for you?
L = [1, -5, 7, -9]
sorted(L, key=abs) [1, -5, 7, -9]
func = "abs"
sorted(L, key=eval(func)) [1, -5, 7, -9]
func = "abs(x)"
sorted(L, key=lambda x: eval(func))
[1, -5, 7, -9]

Bye,
bearophile

Thanks, that works great!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,142
Latest member
arinsharma
Top