calling a function from string

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Oct 22 19:26:14 EDT 2007


On Mon, 22 Oct 2007 23:16:38 +0000, Steven D'Aprano wrote:

>> how could I call a_string as function?
> 
> Others have suggested eval() and exec. Both will work, but have MAJOR
> security implications.

Oh, and they are seriously slower too.

>>> import timeit
>>> timeit.Timer('f("2.3")', 
... 'f = float').repeat() # time using 1st class function
[1.7266130447387695, 0.97645401954650879, 0.97271394729614258]
>>> timeit.Timer('eval("float")("2.3")'
... ).repeat() # time using eval and a string
[20.628923177719116, 19.70452094078064, 19.783280849456787]


-- 
Steven.



More information about the Python-list mailing list