Reputation: 41
Is there any possibility to specify how many arguments a lambda as a function argument can take?
For example:
def func(k=lambda x:return x**2):
return k
Could i specify, if k is not the standard lambda, that k is supposed to take exactly one argument?
Max
Upvotes: 2
Views: 447
Reputation: 37606
You could do something like this using inspect.getargspec
:
import inspect
def func (k = lambda x: x ** 2):
if not callable(k) or len(inspect.getargspec(k).args) != 1:
raise TypeError('k must take exactly one argument.')
# Do whatever you want
Note that the above will miserably fail with something like (while it shouldn't):
func (lambda x, y = 8: x + y)
...so you will need something a bit more complicated if you want to handle this case:
import inspect
def func (k = lambda x: x ** 2):
if not callable(k):
raise TypeError('k must be callable.')
argspec = inspect.getfullargspec(k)
nargs = len(argspec.args)
ndeft = 0 if argspec.defaults is None else len(argspec.defaults)
if nargs != ndeft + 1:
raise TypeError('k must be callable with one argument.')
# Do whatever you want
Upvotes: 6