1

Possible Duplicate:
How to get the original variable name of variable passed to a function

Is there something like below in python where based on the name of the parameter passed to a function we can execute conditional statements like below.

def func(a,b,c,d)

if fourth paramter = d:
#code

elif fourth parameter = e:
#code

else:

#code

   def main():
         func(a,b,c,d)
         func(a,b,c,e)
Community
  • 1
  • 1
user1927396
  • 449
  • 1
  • 9
  • 21
  • 2
    Have you tried using `kwargs` instead? – tpg2114 Jan 01 '13 at 21:28
  • Whenever you need to do something this strange, you're usually much better off to take 2 (or 10) steps back and observe your overall architecture and look what is wrong with it.. most likely there's a much better solution for the overall problem. – Voo Jan 01 '13 at 23:32

2 Answers2

5

You should use keyword arguments:

def func(a, b, c, **kwargs):
    if 'd' in kwargs:
        ....
    elif 'c' in kwargs:
        ....

This is not exactly equivalent to what you want, though. If you want to ensure that d or e is the fourth parameter, that would be more troublesome.

Then you could try something like:

def func(a, b, c, d=None, e=None):
    if d is not None and e is None:
        ....
    elif e is not None and d is None:
        ....

Note that this is not exactly what you're asking. It will not access the "original" name of the variable passed to the function as a positional argument, as in the question linked by Stuart. You shouldn't even try to do that, it's pointless.

Community
  • 1
  • 1
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • @LevLevistsky - i have written a sample code http://pastie.org/5607854 based on your suggestion..my question is am not passing any value to d or e while calling the func..just leaving as d='' or e='' ,is that a problem?I only want to know if the last paratmer is d or e,it seems to work for me though,I just want to make sure – user1927396 Jan 01 '13 at 21:53
  • @user1927396 It's fine; but if you don't need to pass a value with the argument in your real code, why don't you just accept a string as the 4th argument that is either `'c'` or `'d'` and call like `func(1, 2, 3, 'e')` or `func(1, 2, 3, 'd')`. – Lev Levitsky Jan 01 '13 at 22:23
0

kwargs will not give you exactly what you want, but it can be close:

def func(a, b, c, **kwargs):
   if 'd' in kwargs:
       print "do something"
   elif 'e' in kwargs:
       print "do something else"


 def main():
     func(a = 1 ,b = 2 ,c = 3, d = 'some_value')
     func(a = 1 ,b = 2 ,c = 3, e = 'some_value')
Yavar
  • 434
  • 5
  • 13