On 7 July 2013 05:48, Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote: > On Sun, 07 Jul 2013 05:17:01 +0100, Joshua Landau wrote: > >> On 7 July 2013 04:56, Steven D'Aprano >> <steve+comp.lang.pyt...@pearwood.info> wrote: > ... >>> def promote(x): >>> if isinstance(x, str): raise TypeError return float(x) > >>>>> from operator import methodcaller >>>>> safe_float = methodcaller("__float__") > > Nice! > > That's almost as fast as calling float. That will probably do :-)
*Almost* as fast? %~> \python -m timeit -s "safe_float = __import__('operator').methodcaller('__float__'); n = 423.213" "float(n)" 1000000 loops, best of 3: 0.398 usec per loop %~> \python -m timeit -s "safe_float = __import__('operator').methodcaller('__float__'); n = 423.213" "safe_float(n)" 1000000 loops, best of 3: 0.361 usec per loop %~> \python -m timeit -s "safe_float = __import__('operator').methodcaller('__float__'); n = 423" "float(n)" 1000000 loops, best of 3: 0.468 usec per loop %~> \python -m timeit -s "safe_float = __import__('operator').methodcaller('__float__'); n = 423" "safe_float(n)" 1000000 loops, best of 3: 0.436 usec per loop Actually, it's a fair bit faster (yes, I am purposely not showing you the results for Decimals). -- http://mail.python.org/mailman/listinfo/python-list