Home > database >  Passing numeration in while loop to inner function which was passed as a outer function variable in
Passing numeration in while loop to inner function which was passed as a outer function variable in

Time:10-08

I am trying to run a function as a variable in another function, however the first function has a variable that is only being specified in the second function. I do not think it is good practice, but I guess I programmed myself in a corner.

def in_func(n, p):
    print(p)
    print(f'Num {n}')

def out_func(func):
    n = 0
    while n < 10:
        func(n)
        n  = 1
p = 8
out_func(in_func(n, p))

What is the best practice or solution to a problem such as this?

CodePudding user response:

There is no need to use n when passing the in_func as an argument:

def in_func(n):
    print(f'Num {n}')


def out_func(func):
    n = 0
    while n < 10:
        func(n)
        n  = 1


out_func(in_func)

Edit

Pretending the updated syntax works and does something meaningful (had to adjust to even run it), I guess your only option would be to declare the n variable globally. Then returning in_func from itself to be called by out_func:

def in_func(n, p):
    print(p)
    print(f'Num {n}')
    return in_func


def out_func(func):
    global n
    n = 0
    while n < 10:
        func(n, p)
        n  = 1


n = 10
p = 8
out_func(in_func(n, p))

In the end, maybe they don't need to be the same variable?

def in_func(n, p):
    print(p)
    print(f'Num {n}')
    return in_func


def out_func(func):
    n_b = 0
    while n_b < 10:
        func(n_b, p)
        n_b  = 1


n_a = 10
p = 8
out_func(in_func(n_a, p))

CodePudding user response:

You are calling in_func and passing the result to out_func. Instead, you can e.g. define a lambda function that accepts only the n parameter while using p from the current scope...

p = 8
out_func(lambda n: in_func(n, p))

... or use functools.partial to the same effect:

from functools import partial
p = 8
out_func(partial(in_func, p=p))
  • Related