Retrieving Original Variable Names in Python Functions
In Python, it may seem desirable to obtain the original name of a variable when it is passed to a function. However, this task is not directly supported by the language.
To address this, one can leverage the inspect module, though it is not recommended due to potential drawbacks and drawbacks.
<code class="python">import inspect def foo(a, f, b): frame = inspect.currentframe() frame = inspect.getouterframes(frame)[1] string = inspect.getframeinfo(frame[0]).code_context[0].strip() args = string[string.find('(') + 1:-1].split(',') names = [] for i in args: if i.find('=') != -1: names.append(i.split('=')[1].strip()) else: names.append(i) print(names) def main(): e = 1 c = 2 foo(e, 1000, b=c) main()</code>
Output:
['e', '1000', 'c']
Important Notes:
The above is the detailed content of Can You Retrieve Original Variable Names in Python Functions?. For more information, please follow other related articles on the PHP Chinese website!