0

I need to make a function which accepts just an specific kind of functions how parameters, for example just binaries functions. I tried with this, but it doesn't work properly:

from typing import Callable, Any

def es_binaria(f:Callable[[Any,Any],Any]):
    print("Es función binaria")

def f1(a): return a
def f2(a,b): return a+b
def f3(a,b,c): return a+b+c

es_binaria(f1)
es_binaria(f2)
es_binaria(f3)

Look the output, it accepts any kind of function!

Es función binaria
Es función binaria
Es función binaria

Please tell me how I could ensure that my function just accepts binaries functions? (for example)

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Ali Rojas
  • 549
  • 1
  • 3
  • 12

1 Answers1

1

Python is a dynamically typed language. The parameter types you're adding are 'hints', not requirements. Meaning if you want the function to work properly, you should pass this type of parameter to the function.

There is no way to add requirements to the parameter list unless you make assertion statements within the function:

import types
from typing import Callable, Any

def es_binaria(f:Callable[[Any,Any],Any]):
    if type(f) == types.FunctionType: #Check type of f
        print("Es un función")
    else:
        print("No es un función")


def f1(a): return a

es_binaria(1)
es_binaria('string')
es_binaria(f1)
deseuler
  • 408
  • 2
  • 8
  • 2
    "Stictly typed" isn't really a defined term. Python is *strongly* typed, but it is also *dynamically* (as opposed to *statically*) typed, meaning that the type hint only has meaning to a tool like `mypy`, not the Python interpreter itself. – chepner May 25 '21 at 18:15
  • Good catch. I meant *statically* typed. – deseuler May 25 '21 at 18:20
  • Thanks a lot @deseuler! So I can't check the number of parameters of a "parameter-function", just like in C++, that's right? – Ali Rojas May 26 '21 at 00:29
  • 1
    Thats technically correct. Python doesnt have overloaded functions because of this. Its convention to use keyword arguments and set default values for the parameters that arent always used. Another potentially really useful resource would be learning the [use of args and kwargs](https://stackoverflow.com/questions/3394835/use-of-args-and-kwargs). That is also a common method for implementing functions in python with a variable quantity of parameters. – deseuler May 26 '21 at 01:38