Can You Retrieve Original Variable Names in Python Functions?

Barbara Streisand
Release: 2024-10-31 17:34:02
Original
986 people have browsed it

Can You Retrieve Original Variable Names in Python Functions?

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>
Copy after login

Output:

['e', '1000', 'c']
Copy after login

Important Notes:

  • This method should be considered a hack and not used in production code.
  • It can break in certain situations, such as when using nested functions or lambda expressions.
  • There are alternative approaches, such as passing the variable name as an additional argument.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template