Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between simple Python function call and wrapping it in cProfile.run()

I have a rather simple Python script that contains a function call like

f(var, other_var)

i.e. a function that gets several parameters. All those parameters can be accessed within f and have values.

When I instead call

cProfile.run('f(var, other_var)')

it fails with the error message:

NameError: "name 'var' is not defined"

Python version is

Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin

What's going on here?

like image 687
Daniel Beck Avatar asked Sep 02 '25 10:09

Daniel Beck


1 Answers

This is because cProfile attempts to exec the code you pass it as a string, and fails because, well, var is not defined in that piece of code! It is using the variables in the scope of the call to run(), but since you haven't told cProfile about them it doesn't know to use them. Use runctx instead, since it allows you to pass in the locals and globals dictionaries to use for the execed code:

cProfile.runctx( "...", globals(), locals() )
like image 123
Katriel Avatar answered Sep 05 '25 00:09

Katriel