1

Thanks in advance for time spent on this enquiry. I am curious to know if the following is possible. For the below code, is there syntax that will allow you to define an argument for a function (referenced by a dictionary) that is outside of the functions' "tier"?

For this example: I have a main function, mainFunction(key). I can call either mainFunction0 or 1 with the last line mainFunction(mainReferences[0]) IE changing the key to either a 0 or 1 concatenates the reference for the function name to be called.

But what if... I want mainFunction0 to have some sort of argument (one or multiple arguments), that I want to reference with,

mainFunction(mainReferences[0])

I have tried the following, but none seem to work.

mainFunction(mainReferences[0])(1)

mainFunction(mainReferences[0], 1)

Where the additional "1" in either case is the input for "testArg0" within function mainFunction0(testArg0).

Can this be done? If so, is it also possible to enter multiple "outside of tier" arguments?

Cheers!

def mainFunction(key):

    def mainFunction0(testArg0):
        if testArg0 == 1:
            print("main function 1")
        else:
            pass

    def mainFunction1():
        print("main function 1")

    locals()['mainFunction' + key]() 

mainReferences  = ["0", "1"]

mainFunction(mainReferences[0])
  • Possible duplicate of [How to call a function within a function from another function in Python?](https://stackoverflow.com/questions/48049474/how-to-call-a-function-within-a-function-from-another-function-in-python) – Stanley Aug 31 '18 at 13:45
  • Yes, the question I asked was indeed very similar to that other article, but I had a specific need to solve this issue with a dictionary. The other article, while very similar, would not have answered my question. @blhsing was able to solve this issue. –  Sep 02 '18 at 22:52

1 Answers1

0

You can either make mainFunction accept variable arguments:

def mainFunction(key, *args, **kwargs):

    def mainFunction0(testArg0):
        if testArg0 == 1:
            print("main function 1")
        else:
            pass

    def mainFunction1():
        print("main function 1")

    locals()['mainFunction' + key](*args, **kwargs)

mainReferences  = ["0", "1"]

mainFunction(mainReferences[0], 1)

or make mainFunction return a function object and let the caller make the actual call:

def mainFunction(key):

    def mainFunction0(testArg0):
        if testArg0 == 1:
            print("main function 1")
        else:
            pass

    def mainFunction1():
        print("main function 1")

    return locals()['mainFunction' + key]

mainReferences  = ["0", "1"]

mainFunction(mainReferences[0])(1)
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Thanks @blhsing. The top example you provided did the trick. Can you please also explain the bottom example, as I can't see what you did different from the original example I gave? Cheers! –  Sep 02 '18 at 10:36