You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python模块函数调用globals()无法获取当前实例全局变量求助

Solution to Access Caller's Global DataFrames from a Module Function

Let’s start by unpacking the core issue: your curDFs() function uses globals() inside your module, which always points to the module’s own global namespace—not the namespace of the script that calls it. To make it work as intended, we need to tap into the caller’s global variables instead.

Step 1: Use Python’s inspect Module to Access the Caller’s Context

The inspect module lets us peek into the call stack, which we can use to grab the global namespace of the code that invoked curDFs().

Modified my_module.py Code

# my_module.py
import pandas as pd
import inspect

module_dataframe = pd.DataFrame({'yourName'}, columns=['Name'])

def curDFs():
    # Grab the frame of the code that called this function (one level up in the stack)
    caller_frame = inspect.currentframe().f_back
    # Extract the caller's global variables
    caller_globals = caller_frame.f_globals
    
    df_list = []
    # Iterate through the caller's global variables
    for var_name, var_value in caller_globals.items():
        # Use isinstance for reliable type checking (better than string comparisons)
        if isinstance(var_value, pd.DataFrame):
            df_list.append(var_name)
    
    # Clean up the frame reference to avoid potential memory leaks
    del caller_frame
    return df_list

Key Fixes & Improvements:

  • Caller frame access: inspect.currentframe().f_back gets us the frame object of the script that called curDFs(), so we can pull its global variables via f_globals.
  • Safer type checking: Using isinstance() instead of comparing string representations of type() avoids edge cases where type strings might vary across environments.
  • Memory cleanup: Deleting the frame reference prevents lingering memory links, a good practice when working with call stacks.

Test the Solution in new_window.py

# new_window.py
import my_module as mm

# Create a DataFrame in the current script's global namespace
new_dataframe = mm.pd.DataFrame({'name'}, columns=['YourName'])

# Now curDFs() returns the caller's DataFrame, not the module's
print(mm.curDFs())  # Output: ['new_dataframe']

Why This Works

When you call mm.curDFs() from new_window.py, the inspect code grabs the context of that call, extracts new_window.py's global variables, and filters for pandas DataFrames. This makes the function dynamic—you can import and use it in any script, and it will always return the DataFrames from that script’s global namespace.


内容的提问来源于stack exchange,提问作者M.Barkiewicz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 08:27:28