2

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

2
  • Why are you taking a lamda as an argument? Also what you have in your question is not valid python Commented Mar 23, 2016 at 15:01
  • Also calling the lambda with not enough args would error so you could just catch that Commented Mar 23, 2016 at 15:06

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.