Accessing the name of an actual parameter

Jean-Michel Pichavant jeanmichel at sequans.com
Tue Jan 26 12:12:48 EST 2010


Duncan Booth wrote:
> Gary Herron <gherron at islandtraining.com> wrote:
>
>   
>> It's naive to think this question even makes sense.  There are many ways 
>> f can be called which don't involve a parameter:
>>
>> f(42)
>> f(time())
>> f(a+123)
>> f(sin(a))
>> f(f(1))
>>
>> and so on. 
>>     
>
> So long as the OP doesn't care if they get no names or several name that 
> might not matter. However, explicitly passing in the name you want to use 
> is likely to be more useful.
>
>   
>>>> def getcallersnames(obj):
>>>>         
> 	f = inspect.currentframe().f_back.f_back
> 	return [name for name in f.f_locals if f.f_locals[name] is obj]
>
>   
>>>> def bip(x):
>>>>         
> 	print getcallersnames(x)
>
> 	
>   
>>>> def foo(bar):
>>>>         
> 	baz = bar
> 	bip(baz)
> 	bip(baz+1)
>
> 	
>   
>>>> foo(3)
>>>>         
> ['bar', 'baz']
> []
>   
How do you  know which between baz and bar has been used ? Here you get 
all names (in locals()) referencing the object passed in argument, you 
don't get the one actually used for  the call.

Another issue:

class Foo:
    test = 'test'

def foo(bar):
    bip(bar.test)

f = Foo()

foo(f)
[]


That restricts pretty much the use of getcallersnames.
As said before, there is hardly any legit design which would require to 
know the actual refrence used to pass a parameter.

JM



More information about the Python-list mailing list