Converting a strng to an anonymous function

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Mon Sep 29 17:41:14 EDT 2008


On Sep 29, 11:25 pm, Nathan Seese <uninver... at lavabit.com> wrote:
> 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



More information about the Python-list mailing list