0

I've been thinking about this question for a while, and I can't seem to find any related questions to it, probably because I don't know the proper terminology for what I'm looking for.

Is there any condition for an if-else statement in a function that is reliant on which other function is doing the calling? Such as:

def FUNC():
    if func1 called FUNC:
        statement
    elif func2 called FUNC:
        statement

def func1():
    FUNC()

def func2():
    FUNC()

I'm not sure what purpose there would be behind doing this, but I just wanted to know if it was an available option. Thank you.

SignalProcessed
  • 371
  • 4
  • 16
  • 2
    pass different params perhaps? – Van Peer Oct 24 '17 at 14:59
  • 1
    Pass an `argument` that is unique to each function and identify using that from where the call happened. – Kaushik NP Oct 24 '17 at 14:59
  • 2
    This is what `arguments` were invented for. Pass an argument to your function, telling it from where it was called. – offeltoffel Oct 24 '17 at 15:00
  • 2
    Technically you can take the call stack and find the nearest calling frame and use that... The number of real world cases you'd need to do this apart from profiling or similar though is pretty much none. Also, if you're writing functions that care who called them and from where - you should rethink the design :) – Jon Clements Oct 24 '17 at 15:15

1 Answers1

1

Solution: pass an argument.

def FUNC(who_called_me):
    if who_called_me == 'func1':
        # statement
    elif who_called_me == 'func2':
        # statement

def func1():
    FUNC(who_called_me='func1')

def func2():
    FUNC(who_called_me='func2')

The argument (who_called_me) does not have to be of type string, but can also be an integer, boolean or an object.

offeltoffel
  • 2,691
  • 2
  • 21
  • 35