Consider the following scenario: you have a function that requires the name of a variable as an argument to perform some operations based on that name. Is there a way to obtain the original variable name within the function?
To answer this question, let's explore a method utilizing the inspect module that allows you to retrieve the calling context and extract the variable names from the code context.
<code class="python">import inspect def foo(a, f, b): # Get the stack frame of the calling function frame = inspect.currentframe() # Move up one level to get the frame of the calling context frame = inspect.getouterframes(frame)[1] # Get the source code context of the calling context string = inspect.getframeinfo(frame[0]).code_context[0].strip() # Extract the argument names from the code context args = string[string.find('(') + 1:-1].split(',') names = [] for i in args: if i.find('=') != -1: # Handle keyword arguments names.append(i.split('=')[1].strip()) else: # Handle positional arguments names.append(i) print(names) def main(): e = 1 c = 2 foo(e, 1000, b = c) main()</code>
Explanation:
Example Output:
['e', '1000', 'c']
Note: This approach involves inspecting the call stack and interpreting the source code context, which is fragile and prone to errors. It is not recommended for practical use and should only be considered for academic or entertainment purposes.
The above is the detailed content of Can You Extract Original Variable Names from Function Arguments in Python?. For more information, please follow other related articles on the PHP Chinese website!