0

i want to use multiple functions via one outer function. the argument is a string and upon that string i want to create/pass arguments for inner functions. how is that possible?

def outer_function(arg1):
    
    arg2 = 'random_text' + str(arg1)
    arg3 = 'random_text' + str(arg1)
    
    def inner_function(arg2,arg3):
        global var
        do_something ...
    return inner_function()

my error i get is :

TypeError: inner_function() missing 2 required positional arguments:
4
  • 1
    inner_function(arg2, arg3)? The argument names of your inner_function as written shadow the names of those variables in your outer_function. Which means they get overwritten inside the inner_function by whatever arguments are passed when you call inner_function. Commented Dec 7, 2020 at 16:50
  • 1
    Just turn def inner_function(arg2,arg3): To def inner_function(): But seriously, what the point of doing so? Commented Dec 7, 2020 at 16:50
  • 1
    You don't have to pass the outer function variables as parameters to the inner function to use them from inner function, these variables are called closures, look them up. Commented Dec 7, 2020 at 16:51
  • Well, How about passing the needed arguments? return inner_function(arg2, arg3) Commented Dec 7, 2020 at 16:53

2 Answers 2

3

Don't use global, and don't specify the variables as arguments if you're not passing them as arguments. Functions automatically have access to values from the enclosing scope.

def outer_function(arg1):
    arg2 = 'random_text' + str(arg1)
    arg3 = 'random_text' + str(arg1)

    def inner_function():
        return arg2 + arg3

    return inner_function()

>>> outer_function(" foo ")
'random_text foo random_text foo '
Sign up to request clarification or add additional context in comments.

1 Comment

Yes this is the right way to do it. I am surprised to see people skip over the topic of closure which is one of the easiest topics to learn in programming.
0

You didn't passed arguments or parameters in return inner_funtion()below code can help

def outer_function(arg1):
    arg2 = 'random_text' + str(arg1)
    arg3 = 'random_text' + str(arg1)
    def inner_function(arg2,arg3):
        global var
        do_something ...
    return inner_function(arg2,arg3)

3 Comments

thank you this on helped. but after the first inner_function is executed it will stop and not execute the second. is there something i will have to add oder command?
i use multiple inner functions and they all have arg2 and arg3 as arguments#
Can you elaborate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.