0

I need to optimize my number of lines by making one function instead of several i want to have an output :

0 0
0 1
0 2
0 3
0 4

and as few functions as possible. I need to call it by function 1 that i don't have access to.

my code looks like this:

# I have a direct access to this function and I want to call it by giving it val and other_val
def f0(val, other_val=None):
    print(val, other_val)

# I don't have a direct access to this function because it's in a library
def f1(function):
    function(0)


if __name__ == '__main__':
    # I need to call this specific function and pass other_val aswell but can't because f1 is in a library
    f1(f0)  # other_val = 0
    f1(f0)  # other_val = 1
    f1(f0)  # other_val = 2
    f1(f0)  # other_val = 3
    f1(f0)  # other_val = 4
L1RG0
  • 17
  • 4
  • Try using global variable. Exclude other_val from f0 definition, create `last = 0` outside of function and then access and modify it from f0 using `global` keyword like `global last` at the beginning of function. – STerliakov May 10 '21 at 10:51
  • To wrap an existing function you might want to use [functools.partial](https://docs.python.org/3/library/functools.html#functools.partial) ([HowTo](https://stackoverflow.com/a/15331841/1185254)). – alex May 10 '21 at 10:58

3 Answers3

0

I figured something like this would work:

other = 0
def f2(function, othr):
    global other
    other = othr
    return function

# I have a direct access to this function and we want to call it by giving it val and other_val
def f0(val):
    print(val, other)

# I don't have a direct access to this function because it's in a library
def f1(function):
    function(0)


if __name__ == '__main__':
    # I need to call this specific function and pass other_val aswell
    f1(f2(f0, othr=0))  # other_val = 0
    f1(f2(f0, othr=1))  # other_val = 1
    f1(f2(f0, othr=2))  # other_val = 2
    f1(f2(f0, othr=3))  # other_val = 3
    f1(f2(f0, othr=4))  # other_val = 4
L1RG0
  • 17
  • 4
0

I suggest using only single function:

# I have a direct access to this function and I want to call it by giving it val and other_val

other = 0
def f0(val):
    global other
    print(val, other)
    other += 1

# I don't have a direct access to this function because it's in a library
def f1(function):
    function(0)


if __name__ == '__main__':
    # I need to call this specific function and pass other_val aswell but can't because f1 is in a library
    f1(f0)  # other_val = 0
    f1(f0)  # other_val = 1
    f1(f0)  # other_val = 2
    f1(f0)  # other_val = 3
    f1(f0)  # other_val = 4
STerliakov
  • 4,983
  • 3
  • 15
  • 37
0

You can avoid using a global by using a higher-order function instead.

def f0(other_val=None):
    def wrapped_f0(val):
        print(val, other_val)
    return wrapped_f0

def f1(function):
    function(0)


if __name__ == '__main__':
    f1(f0(0))
    f1(f0(1))
    f1(f0(2))
    f1(f0(3))
    f1(f0(4))
big_bad_bison
  • 1,021
  • 1
  • 7
  • 12