Accessing the name of an actual parameter

H

Hellmut Weber

Hi,

consider the following piece of code, please

----- -----

def f(param):
nameOfParam = ???
# here I want to access the name of the variable
# which was given as parameter to the function
print nameOfParam, param
return

if __name__ == __main__:

a = 1
f(a)

b = 'abcd'
f(a)

----- -----

The output should be:

'a' 1
'b' 'abcd'

----- -----

I tried to look at globals() and locals(), gave a look to the frames
(sys._getframe(0) and sys._getframe(1),
but did not see a possibility to access the information a want

How can this be done?

TIA

Hellmut
 
A

Alf P. Steinbach

* Hellmut Weber:
consider the following piece of code, please

----- -----

def f(param):
nameOfParam = ???
# here I want to access the name of the variable
# which was given as parameter to the function
print nameOfParam, param
return

if __name__ == __main__:

a = 1
f(a)

b = 'abcd'
f(a)

----- -----

The output should be:

'a' 1
'b' 'abcd'

----- -----

I tried to look at globals() and locals(), gave a look to the frames
(sys._getframe(0) and sys._getframe(1),
but did not see a possibility to access the information a want

How can this be done?

Not in any efficient way. A debugger can do it, and you can do it in the same
way as a debugger, checking stack frames and the source code. But if it's
debugging that you're after then use a debugger -- that's what they're for.

Otherwise, just change the way that you invoke the routine.

For example,
... print( kwa )
...

Cheers & hth.,

- Alf
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top