簡體   English   中英

Python - 調用使用 globals() 的模塊 function 但它只從模塊中提取 globals() 而不是當前的 python 實例

[英]Python - Calling a module function which uses globals() but it only pulls globals() from the module not the current python instance

python 版本:3.8.1

平台 = Windows 10 親

開發環境:visual studio code、jupyter notebook、命令行

我有從個人模塊導入的 function 以查找所有當前 Pandas - memory 或 globals 中的數據幀()。 但是我只從模塊中獲取 globals() 。 (我現在知道 globals() 僅適用於調用它的模塊) <--- 這是我的問題!

如上所述,我知道這甚至無法通過常規方法遠程完成。 這是我從頭到尾的代碼。 **請注意,我正在從模塊中調用我的 function,這只會從我當前的 python 實例的 globals() 中返回“module globals()”而不是“local globals()”。

來自“my_module”模塊的代碼:

# 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   

所以你可以看到我在我的模塊中創建了一個 Dataframe 並創建了 function curDFs() 以返回 globals() 中作為數據幀的變量的名稱。

以下是來自全新 python session 的代碼:

# 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”變量。 我該怎么做? 我被卡住了,其他所有帖子都只是介紹了全局和本地 scope 或如何創建全局變量的 config.py 文件。 但是,這必須是動態的,而不是 static,因為我看到了 congig.py 文件。

我認為在我啟動的每個實例中都必須構建這個 function 會很麻煩。 我希望能夠導入它,這樣我就可以與其他人共享或最大限度地減少由於必須在每個新的 python 實例中復制粘貼或重新輸入而導致的重復輸入。

非常感謝這里的任何評論或幫助。

抱歉,看來我沒有仔細回答您的問題。

對於您的問題,我在這個問題上找到了提示。

似乎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 語言參考,第 4.2.2 章(名稱解析) (強調添加):

如果 global 語句出現在一個塊中,則該語句中指定的名稱的所有使用都指的是該名稱在頂級名稱空間中的綁定。 通過搜索全局命名空間(即包含代碼塊的模塊的命名空間)和內置命名空間(內置模塊的命名空間)來解析頂級命名空間中的名稱。 首先搜索全局命名空間。 如果在那里找不到名稱,則搜索內置名稱空間。 全局語句必須在名稱的所有使用之前。

在您的案例中,包含代碼塊的模塊的命名空間是my_module.py的命名空間,並且只有my_module.py的命名空間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM