How to save a function, with predefined parameters, in a python variable?

Asked

Viewed 352 times

2

Currently I can save functions in variables as follows:

def somar_iguais(lista, referencia):
  resultado = 0
  for x in lista:
    if lista[x] == referencia:
      resultado += referencia
  return resultado

SOMAR = somar_iguais

def main():
  numeros = [1,1,2,3]
  SOMAR(numeros, 1)

I want to save function sum equal with the parameter reference already defined, so that when I call the function by variable name I need to provide only the parameter that is not yet defined. Example:

def somar_iguais(lista, referencia):
  resultado = 0
  for x in lista:
    if lista[x] == referencia:
      resultado += referencia
  return resultado

SOMAR_UNS = somar_iguais(referencia: 1)
SOMAR_DOIS = somar_iguais(referencia: 2)

def main():
  numeros = [1,1,2,3]
  SOMAR_UNS(numeros)
  SOMAR_DOIS(numeros)

Is it possible to do this in Python 3.7.3? How can I do it?

1 answer

3


You can do this through the function functools.partial:

from functools import partial

somar_um = partial(somar_iguais, referencia=1)
somar_dois = partial(simar_iguais, referencia=2)

So in doing somar_um(numeros) will be the same as do somar_iguais(numeros, referencia=1).

  • It worked! Thank you very much :D

  • I found another solution: somar_um = lambda x: somar_iguais(x, 1)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.