Converting a strng to an anonymous function

Nathan Seese uninverted at lavabit.com
Mon Sep 29 18:35:00 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

Thanks, that works great! 



More information about the Python-list mailing list