Python如何获取特定范围内变量的字典(甚至列表);比locals/globals()更具体

2024-04-24 10:09:07 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,标题几乎说明了一切。你知道吗

例如,让我们看看下面的示例代码:

## How can I obtain a dict/list (like locals()) of all the variables in second and/or third layer scopes via a command 
# coming from the first layer?
## Or another example would be how could I obtain the variables "locals() style" from the thirdlayer via a 
# command from the second layer?
# essentially can a parent function/class access a list/dict of a child function
# or class??

def firstLayer():
     a = 4.7
     q = locals()
     print(q)
     # local vars of 1st layer
     def secondlayer():
          b = 7
          r = locals()
          print(r)
          # local vars of 2nd layer
          def thirdlayer():
               c = False
               s = locals()
               i = globals()
               print('c:\n', c, "\nglobals from 3rd layer:\n\t", i)
              # local vars of 3rd layer
          thirdlayer()

     secondlayer()
firstLayer()

sample_var = globals()
print(sample_var)
# returns the list of global variables

为了重申我在代码注释中所说的,本质上是他们的任何方法,我可以得到一个“子”范围的所有局部变量的列表吗?我知道函数是关闭的,但如果它们无法做到这一点,那么它们的任何更复杂的代码都可以实现这一点,如果需要,我可以将其集成到函数或类中。你知道吗

编辑: 更详细地说,这是我所处的情况。你知道吗

def varsfunc():
    font1 = "Harlow Solid"
    grey = '#454545'
    font2 = 'Mistral'
    font3 = 'Italic 35px Times New Roman'
    pnk = 'pink'
    grn = 'green'
    return locals()

本质上,我正在创建一个模块,用户必须创建某种类型的函数,这些函数列出了他们想要声明用于修改css文件的所有变量。基本上,我希望允许用户不必键入“return locals()”。我想通过让最终用户将上面的示例函数包装在一个decorator中来实现它,这个decorator相当于返回我想要的确切范围的locals()。装饰工不为我工作,因为它在外部范围内。你知道吗

更清楚地说: 我需要一个decorator/函数来包装另一个函数(即decorator),它可以访问并创建子元素的列表。你知道吗

def module_decorator_func_thing():
     r = command_that_acts_like_locals()_but_for_child_scopes
     def user_var_list():
          font1 = 'green'
          font2 = 'pink'
     # back in "module_decorator_func_thing"'s scope
     print(r) # this variable should contain only a dict/list containing the
     # the following:
     # r = {'font1': 'green', 'font2': 'pink')

当前用户需要这样做:

def vars_func_container():
     font1 = 'green'
     font2 = 'pink'
     return locals() #  <---- I want the user to not have to type this and for 
    # a function decorator to take care of it instead possibly.

@aguy和其他想要更多信息的人的信息。 我通过你们的小贴士获得的字典/列表将被发送到这个函数来完成程序的真正工作。 (如果我要开始使用列表,我需要转换成字典,但这对我来说不是问题。) 变量dict与此函数一起用于“compile/compyle”(Pun on The word'Python'+'compile)并插入到“variables”参数中。e、 你执行这样的函数。你知道吗

compyle("My sample title", return_stylesheet_from_func(*insert .css filename), 
return_variables_from_function(*insert function containing variables*), "**True/False to turn on compilation**", 
"**True/False to turn on annotations/suggestions**")

def compyle(title, style_sheet, variables, boolean=False, boolean2=True):
    """
    :param title: The name you wish your .css file to be named.
    :param style_sheet: The name of the multi-line string that will compose your .css file
    :param variables: The name of the dictionary containing your .pcss variables
    :param boolean: A.K.A the "Compiler Parameter" - Turns the compiler on or off
    :param boolean2: A.K.A the "Annotation Parameter" - Turns annotations on or off
    :return: returns compiled .pcss text as normal .css style text to be utilized with .html
    """
    # -----------------------------------
    file_name = title + ".css"
    replace_num = len(variables.keys())
    counter = replace_num
    content = style_sheet
    # -----------------------------------
    # add theme support with namedtuple's formatted to mimic structs in C/C++
    # this will be a major feature update as well as a nice way to allow the future prospect of integrating C/C++ into
    # the compiler. Info: https://stackoverflow.com/questions/35988/c-like-structures-in-python
    for k, v in variables.items():
        counter -= 1
        content = content.replace(k, v, replace_num)
        if counter == 0:
            break
        else:
            pass
    looped_content = str(content)
    id_content = looped_content.replace("hash_", "#")
    output = id_content.replace("dot_", ".")

    if boolean is True:
        if boolean2 is True:
            output = " /* --- Pyle Sheet --- */\n" + output
            with open(file_name, 'w') as writ:
                writ.write(output)
                writ.close()
                print('compiled successfully; The file was saved as ' + "\"" + file_name + "\".")
        elif boolean2 is False:
            pass
        else:
            logging.warning("An Error Occurred - see module, documentation, or online Q&A for assistance.")
    elif boolean is False:
        if boolean2 is True:
            print('compiled successfully; The file ' + "\"" + file_name + "\"" + "was not saved/created.")
        elif boolean2 is False:
            pass
        else:
            logging.warning("An Error Occurred - see module, documentation, or online Q&A for assistance.")
    else:
        logging.warning('An Error Occurred with the Compile Parameter (See: boolean in pyle_sheets source file) - \ '
                        'see module, documentation, or online Q&A for assistance.')

Tags: oroftheto函数namelayerfalse
2条回答

如果不深入研究,我无法找到任何方法;下面是我想到的最简单的解决方案。你知道吗

工作原理

使用ast模块,我们遍历给定函数的代码并找到所有赋值。在给定的命名空间中计算这些值,并返回此命名空间。你知道吗

代码

import ast
import functools
import inspect

def returnAssignments(f):
    @functools.wraps(f)
    def returner():
        assignments = dict()
        for node in ast.walk(ast.parse(inspect.getsource(f))):
            if isinstance(node, ast.Assign):
                exec(compile(ast.Module([node]), '<ast>', 'exec'),
                     globals(),
                     assignments)
        return assignments
    return returner

用法

from ra import returnAssignments

@returnAssignments
def foo():
    this = 'something'
    that = 37
    the_other = object()

print(foo())

输出

rat@pandion:~/tmp$ python test.py
{'this': 'something', 'that': 37, 'the_other': <object object at 0x10205b130>}

我想知道我在这里提供的这种粗略的解决办法是否对你有用。请注意,我并没有在所有情况下测试它,所以它可能有点粗糙。而且,它以字符串的形式返回所有内容,这是一种可能需要进一步更改的行为。你知道吗

定义函数:

def get_local_vars_from_function(f):
    import inspect
    s = inspect.getsourcelines(f)[0]
    d = {}
    for l in s:
        if '=' in l:
            var, val = l.split('=')
            var = var.strip()
            val = val.strip()
            d[var] = val
    return d

然后使用它:

In[91]: get_local_vars_from_function(user_var_list)
Out[91]: {'font1': "'green'", 'font2': "'pink'"}

相关问题 更多 >