Python调用使用globals()的模块函数,但它只从模块而不是当前Python实例中提取globals()

2024-04-19 03:44:14 发布

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

python版本:3.8.1

平台=Windows 10 pro

开发环境:VisualStudio代码、jupyter笔记本、命令行

我有一个从个人模块导入的函数,用于查找内存或globals()中的所有当前熊猫数据帧。但是,我只从模块中获取globals()。(我现在知道globals()只适用于调用它的模块)<;——这是我的问题

如上所述,我知道这甚至不能用常规方法远程完成。这是我从头到尾的代码**请注意,我正在从模块调用我的函数,这只会从当前python实例的globals()返回“module globals()”而不是“local globals()”

来自“my_模块”模块的代码:

# my_module.py #

import pandas as pd

module_dataframe = pd.Dataframe({'yourName'},columns = ['Name']) # creates dataframe in my module

def curDFs():
   i ='' # create variable before trying to loop through globals() prevents errors when initiating the loop
   dfList = []
   for i in globals():
       if str(type(globals()[i])) == "<class 'pandas.core.frame.DataFrame'>":
           dfList.append(i)
   return df_list   

您可以看到,我正在模块中创建一个数据帧,并创建函数curDFs(),以返回globals()中作为数据帧的变量的名称

下面是全新python会话的代码:

# new_window.py #

import my_module as mm
#not importing pandas since already imported into "my_module"

new_dataframe = mm.pd.DataFrame({'name'},columns = ['YourName'])

#calling globals() here will return the "local global variable"->"new_dataframe" created above

#if i call my "curDFs()" function from the module, I return not 'new_dataframe' but the 'module_dataframe' from the module

mm.curDFs()
#returns
['module_dataframe']

我需要它只返回“new_dataframe”变量。我该怎么做?我被卡住了,每一篇文章都会涉及全局和局部范围,或者如何创建全局变量的config.py文件。但是,这必须是动态的,而不是像我看到的congig.py文件那样是静态的

我认为在我创建的每个实例中都必须构建这个函数会很麻烦。我希望能够导入它,以便与其他人共享,或者最小化由于必须在每个新python实例中复制粘贴或重新键入而导致的重复键入

非常感谢您的任何意见或帮助


Tags: 模块the数据实例函数代码pydataframe
1条回答
网友
1楼 · 发布于 2024-04-19 03:44:14

对不起,我似乎没有仔细考虑你的问题

对于你的问题,我在this问题中找到了一个提示

似乎inspect模块可以执行您想要的操作:

# my_module.py #

import pandas as pd
import inspect

module_dataframe = pd.Dataframe({'yourName'},columns = ['Name']) # creates dataframe in my module

def curDFs():
    caller_frame = inspect.stack()[1]
    caller_module = inspect.getmodule(caller_frame[0])
    return [name for name, entry in caller_module.__dict__.items() if str(type(entry)) == "<class 'pandas.core.frame.DataFrame'>"]

这对我的测试有效,但请注意,在各种情况下,这可能会失败(一些警告在链接的帖子中)


这是预期的行为。根据Python Language Reference, Chapter 4.2.2 (Resolution of Names)(重点加上):

If the global statement occurs within a block, all uses of the name specified in the statement refer to the binding of that name in the top-level namespace. Names are resolved in the top-level namespace by searching the global namespace, i.e. the namespace of the module containing the code block, and the builtins namespace, the namespace of the module builtins. The global namespace is searched first. If the name is not found there, the builtins namespace is searched. The global statement must precede all uses of the name.

在您的案例中,包含代码块的模块的名称空间是my_module.py的名称空间,并且只有my_module.py的名称空间

相关问题 更多 >