Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: variables scope and profile.run

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?

like image 989
Student FourK Avatar asked Dec 30 '11 18:12

Student FourK


People also ask

How are Python variables scoped?

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.

What is scope and lifetime of variables in Python?

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.

Does Python have scope?

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.

What is the scope of global variable in Python?

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.


1 Answers

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.

like image 129
Adam Zalcman Avatar answered Oct 20 '22 00:10

Adam Zalcman