Python模块函数调用globals()无法获取当前实例全局变量求助
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_backgets us the frame object of the script that calledcurDFs(), so we can pull its global variables viaf_globals. - Safer type checking: Using
isinstance()instead of comparing string representations oftype()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

