I want to call profile.run within my function, i.e.:
def g():
...
def f():
x = ...
run.profile('g(x)')
However, it says 'x is not defined' when calling run.profile. As far as I understand, I have to supply import statement before calling g(x) inside string argument to run.profile, and I could do this with global variables.
Is this possible with local variables?
What is Variable Scope in Python? In programming languages, variables need to be defined before using them. These variables can only be accessed in the area where they are defined, this is called scope. You can think of this as a block where you can access variables.
Parameters and variables defined inside a function are not visible from outside. Hence, they have a local scope. 2. The lifetime of a variable is the period throughout which the variable exits in the memory of your Python program. The lifetime of variables inside a function is as long as the function executes.
In Python, the concept of scope is closely related to the concept of the namespace. As you've learned so far, a Python scope determines where in your program a name is visible. Python scopes are implemented as dictionaries that map names to objects. These dictionaries are commonly called namespaces.
A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local.
Instead of using run()
use runctx()
which allows you to supply locals and globals. For example:
>>> import cProfile
>>> def g(x):
... print "g(%d)" % x
...
>>> x=100
>>> cProfile.runctx('g(x)', {'x': x, 'g': g}, {})
g(100)
3 function calls in 0.000 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <stdin>:1(g)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
>>>
See also runctx()
in this document.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With