1

The following code (gratefully gleaned from elsewhere in stackoverflow):

import inspect
def func(first, second, third):
    frame = inspect.currentframe()
    # print(f'frame: {inspect.getargvalues(frame)}')
    args, _, _, values = inspect.getargvalues(frame)
    print(f'function name {inspect.getframeinfo(frame)[2]}')
    for i in args:
        print(f'{i} = {values[i]}')
    return [(i, values[i]) for i in args]

a = 'Test'
b = 'This'
c = 'Now'

func(a, b, c)

prints:

function name func
first = Test
second = This
third = Now

I would like the code to:

  1. Print a = Test, b = This, c = Now instead of first = Test.. etc
  2. According to No. 1 immediately above, print the arguments names passed to *args. So instead of def func(first, second, third): it should be def func(*args): whose expected output should be:

    function name func a = Test b = This b = Now

I am deliberately avoiding using **kwargs (which would solve the problem easily but will require significant change in my code which may not be an option in the immediate term).

P.S. For clarification purposes, I am not looking for a way to get the name of the function (as this is already achieved with the code above) or for a way to get the name of the arguments when the arguments are explicitly named at the function definition. I am only stuck when the arguments are passed via *args (in which case the number or name of arguments cannot be determined until the time the function is being called and the name and the number of arguments are being passed to it)

I am new to Python kindly help!

Mathiokore
  • 21
  • 4
  • To get the name of your function you can use `func.__name__` You cannot print the name of your variables as stated here - https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string Also this feels a lot like homework – letsc Sep 10 '19 at 19:30
  • @letsc The question linked has an answer that DOES tell you how to retrieve the variable names as requested by the OP. A link to the answer: https://stackoverflow.com/a/18425523/3308951. In order to modify the solution to what the OP needs, they need to add another `.f_back` in the initialization of `callers_local_vars`. It should read: `callers_local_vars = inspect.currentframe().f_back.f_back.f_locals.items()` – SyntaxVoid Sep 12 '19 at 22:39
  • Possible duplicate of [Getting the name of a variable as a string](https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string) – wjandrea Sep 12 '19 at 22:43
  • Related: [python obtain variable name of argument in a function](https://stackoverflow.com/q/11583526/4518341) – wjandrea Sep 12 '19 at 22:43

0 Answers0