简体   繁体   English

如何在Python中获取/设置函数的局部变量(从外部)?

[英]How to get/set local variables of a function (from outside) in Python?

If I have a function (in Python 2.5.2) like: 如果我有一个函数(在Python 2.5.2中),如:

def sample_func():
    a = 78
    b = range(5)
    #c = a + b[2] - x

My questions are: 我的问题是:

  1. How to get the local variables (a,b) of the function from outside without using locals() inside the function? 如何在使用函数内部的locals()的 情况下从外部获取函数的局部变量(a,b)? (kind of reflection) (一种反思)
  2. Is it possible to set a local variable (say x ) from outside so that the commented line works? 是否可以从外部设置局部变量(比如说x ),以便注释行有效? (I know it sounds weird). (我知道这听起来很奇怪)。

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: 这是场景:

  1. I have an encrypted python source file containing a python function. 我有一个包含python函数的加密python源文件。
  2. AC extension module decrypts it and builds that function in-memory. AC扩展模块对其进行解密并在内存中构建该功能。
  3. A main python program first calls the C extension with that encrypted file location. 主python程序首先使用该加密文件位置调用C扩展。
  4. Then the main program calls the function that has been built in-memory (by the C extension) 然后主程序调用内存中构建的函数(通过C扩展)
  5. But main program needs to know the local variables of that function (Dont ask me why, it was not me) 但是主程序需要知道该函数的局部变量(不要问我为什么,这不是我)
  6. For some (damn) reason, main program needs to set a variable too (weirdest of all) 对于某些(该死的)原因,主程序也需要设置一个变量(最奇怪)

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; 这是一个黑客攻击,因为没有办法知道co.co_consts中的哪个常量是哪个; this uses a sentinel value to figure it out. 这使用了一个标记值来计算出来。 Depending on whether you can constrain your use cases enough, that might be enough. 根据您是否可以足够约束您的用例,这可能就足够了。

I'm not sure what your use-case is, but this may work better as a class. 我不确定你的用例是什么,但这可能会更好地作为一个班级。 You can define the __call__ method to make a class behave like a function. 您可以定义__call__方法以使类的行为类似于函数。

eg: 例如:

>>> class sample_func(object):
...     def __init__(self):
...         self.a = 78
...         self.b = range(5)
...     def __call__(self):
...         print self.a, self.b, self.x
... 
>>> f = sample_func()
>>> print f.a
78
>>> f.x = 3
>>> f()
78 [0, 1, 2, 3, 4] 3

(this is based on your toy example, so the code doesn't make much sense. If you give more details, we may be able to provide better advice) (这是基于您的玩具示例,因此代码没有多大意义。如果您提供更多详细信息,我们可能会提供更好的建议)

函数运行时函数的局部变化,因此在函数未运行时访问函数的意义不大。

Not sure if this is what you mean, but as functions are objects in Python you can bind variables to a function object and access them from 'outside': 不确定这是不是你的意思,但由于函数是Python中的对象,你可以将变量绑定到一个函数对象并从'outside'访问它们:

def fa():
    print 'x value of fa() when entering fa(): %s' % fa.x
    print 'y value of fb() when entering fa(): %s' % fb.y
    fa.x += fb.y
    print 'x value of fa() after calculation in fa(): %s' % fa.x
    print 'y value of fb() after calculation in fa(): %s' % fb.y
    fa.count +=1


def fb():
    print 'y value of fb() when entering fb(): %s' % fb.y
    print 'x value of fa() when entering fa(): %s' % fa.x
    fb.y += fa.x
    print 'y value of fb() after calculation in fb(): %s' % fb.y
    print 'x value of fa() after calculation in fb(): %s' % fa.x
    print 'From fb() is see fa() has been called %s times' % fa.count


fa.x,fb.y,fa.count = 1,1,1

for i in range(10):
    fa()
    fb()

Please excuse me if I am terribly wrong... I´ma Python and programming beginner myself... 如果我非常错误,请原谅我...我是Python和编程初学者自己......

Expecting a variable in a function to be set by an outside function BEFORE that function is called is such bad design that the only real answer I can recommend is changing the design. 期望函数中的变量由外部函数设置在调用该函数之前是如此糟糕的设计,以至于我可以推荐的唯一真正的答案是改变设计。 A function that expects its internal variables to be set before it is run is useless. 期望在运行之前设置其内部变量的函数是无用的。

So the real question you have to ask is why does that function expect x to be defined outside the function? 所以你要问的真正问题是为什么这个函数期望x被定义在函数之外? Does the original program that function use to belong to set a global variable that function would have had access to? 函数使用的原始程序是否设置了一个函数可以访问的全局变量? If so, then it might be as easy as suggesting to the original authors of that function that they instead allow x to be passed in as an argument. 如果是这样,那么它可能就像向该函数的原始作者建议他们改为允许x作为参数传递一样容易。 A simple change in your sample function would make the code work in both situations: 样本函数的简单更改将使代码在以下两种情况下都起作用:

def sample_func(x_local=None):
  if not x_local:
    x_local = x
  a = 78
  b = range(5)
  c = a + b[2] - x_local

This will allow the function to accept a parameter from your main function the way you want to use it, but it will not break the other program as it will still use the globally defined x if the function is not given any arguments. 这将允许函数以您希望的方式接受主函数中的参数,但它不会破坏其他程序,因为如果函数没有给出任何参数,它仍将使用全局定义的x。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从函数外部访问局部变量以测试它们 - How to access local variables from outside a function in order to test them 如何使函数从Python中的函数外部获取变量? - How to make a function take variables from outside the function in Python? 如何获取python中function中定义的所有局部变量? - How to get all the local variables defined inside the function in python? 如何使用python中另一个函数的局部变量? - How do I use local variables from another function in python? Python:在函数内命名类型并在函数外分配变量 - Python: Naming types and assigning variables outside a function from within a function 从python 3.5中的函数内部修改函数范围之外的变量 - modify variables outside of function scope from within a function in python 3.5 功能之外的Python访问变量 - Python Access Variables Outside of Function 在Python中的函数外部访问变量 - Accessing variables outside a function in Python 我可以获取抛出异常的 Python 函数的局部变量吗? - Can I get the local variables of a Python function from which an exception was thrown? 如何从一个函数调用两个返回的局部变量以在python中的另一个函数中作为条件进行验证? - How to call two returned local variables from a function to verify as a condition in another function in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM