If I have a function (in Python 2.5.2) like:
def sample_func():
a = 78
b = range(5)
#c = a + b[2] - x
My questions are:
Thanks in advance.
EDIT:
Everyone is asking for a use-case. But it is a weird situation. (Don't blame me, I did not create it). Here is the scenario:
Using the global statement If you want to assign a value to a name defined outside the function, then you have to tell Python that the name is not local, but it is global. We do this using the global statement. It is impossible to assign a value to a variable defined outside a function without the global statement.
If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class.
In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.
A local variable is defined inside a function or a block statement and is not accessible outside the function or block. This means that these variables are visible and can only be used by the function in which the variable is defined!
No. A function that isn't being run doesn't have locals; it's just a function. Asking how to modify a function's locals when it's not running is like asking how to modify a program's heap when it's not running.
You can modify constants, though, if you really want to.
def func():
a = 10
print a
co = func.func_code
modified_consts = list(co.co_consts)
for idx, val in enumerate(modified_consts):
if modified_consts[idx] == 10: modified_consts[idx] = 15
modified_consts = tuple(modified_consts)
import types
modified_code = types.CodeType(co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, modified_consts, co.co_names, co.co_varnames, co.co_filename, co.co_name, co.co_firstlineno, co.co_lnotab)
modified_func = types.FunctionType(modified_code, func.func_globals)
# 15:
modified_func()
It's a hack, because there's no way to know which constant in co.co_consts is which; this uses a sentinel value to figure it out. Depending on whether you can constrain your use cases enough, that might be enough.
The function's locals change whenever the function is run, so there's little meaning to access them while the function isn't running.
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