Python: TypeError: <lambda>() takes 0 positional arguments but 1 was given due to assert

17,734

Here's an example to show where you are going wrong and for the purpose of explanation I am assigning the lambdas to variables:

zero_arg_lambda = lambda: "131"  # Takes no args
one_arg_lambda = lambda x: "131"  # Takes one arg

Call zero_arg_lambda with arg (same as your error):

zero_arg_lambda(1)
>>> Traceback (most recent call last):
>>> File "<input>", line 1, in <module>
>>> TypeError: <lambda>() takes no arguments (1 given)

Call one_arg_lambda :

one_arg_lambda(1)
>>> "131"

So in short your code is passing a parameter to the lambda even though you have specified that it does not take one.

The one_arg_lambda example takes a parameter and simply returns the value to the right of the colon. I would recommend reading over the docs on lambda

Or if you don't look there the expected lambda format is:

lambda parameters: expression

Also note the docs on monkeypatch.context.setattr which have a good example of using a lambda expression.

To pin-point it the error in your code is coming from the context.setattr call inside your test.

def test_get_weight_returns_valid_input(monkeypatch):
    with monkeypatch.context() as context:
        # Old line causing error: context.setattr('builtins.input', lambda: "131")
        context.setattr('builtins.input', lambda x: "131")  # Fixed 
Share:
17,734
smokingpenguin
Author by

smokingpenguin

Updated on June 20, 2022

Comments

  • smokingpenguin
    smokingpenguin almost 2 years

    I am new to making unit tests. I'm currently running pytest. I have this Program.py running but when I run pytest on my Program_test.py I've been failing the tests due to these TypeErrors from my where I had my assert line on the code below. I have the program ask the users for an input value or enter to exit the program. I have the 'import pytest' already included in my Program_test.py program.

    Am I using lambda wrong? I'm not sure how to best approach this and get those user inputs to work. This is just testing the get_weight function from users.

    ***It was already fixed. I had a problem with lambda and underneath was very helpful

  • smokingpenguin
    smokingpenguin about 5 years
    So is my syntax wrong on context.setattr? How do I fix this applying with your example on the lambda variables?
  • cullzie
    cullzie about 5 years
    Yes it was wrong as you did not pass an arg to the lambda and context.setattr passes an arg. The fix is in the last block of code in my answer. I have commented out the old code
  • cullzie
    cullzie about 5 years
    Well that's just an assertion error. Perhaps you should be returning an integer from the lambda instead of a string: lambda x: 131 instead of lambda x: "131"
  • smokingpenguin
    smokingpenguin about 5 years
    AWESOME! Thank you! It was fixed