Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does exec("func") convert the inputted function string once or converts it every time the func is called?

More specifically, if I have a code like

exec("a = lambda x:x**2")

>>> a(2)
4
>>> a(3)
9

Will exec be converting the string to a function and evaluating it at the input every time a is called or will it define a as a callable function once and then just refer to it every time a is called after running the exec() function

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

exec executes the code as if you had typed it yourself into the Python interpreter (or your .py file). You can verify this by adding a print call inside of your exec code:

>>> exec("a = lambda x:x**2; print('running')")
running

>>> a(2)
4

>>> a(9)
81

Notice how running is printed only once.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading