2

I'm having a hard time understanding this piece of code. I understand that we are using some mock instead of the API endpoint to save time on the tests.

What I don't understand is the classmethod(lambda cls: self.preapproval) structure. What is the point of using a lambda cls if inside the code I don't use at all the cls.

I hope I'm clear enough, I'd be very happy if someone could shed some light on this one..

Thanks a lot.

@patch("paypaladaptive.api.endpoints.UrlRequest",
       MockUrlRequestPreapproval)
def test_preapproval(self):
    # I don't understand this code, it is very confusing. Why do I need to use a lambda structure if in the code itself I don't use cls (self.preapproval)
    MockUrlRequestPreapproval.preapproval = (
        classmethod(lambda cls: self.preapproval))
    self.assertTrue(self.preapproval.process())
    self.preapproval = Preapproval.objects.get(pk=self.preapproval.pk)
    self.assertNotEqual(self.preapproval.preapproval_key, "")
    self.assertEqual(self.preapproval.status, "created")

2 Answers 2

2

classmethod's first argument needs to be a function that takes one argument or more. Calling any of this will cause an error:

classmethod(self.preapproval) # Not a function
classmethod(lambda: self.preapproval) # Needs one argument

This works, but it's too verbose:

def get_preapproval(cls):
    return self.preapproval

classmethod(get_preapproval)

That's why that code uses lambda.

Probably it can be improved a little bit:

classmethod(lambda _: self.preapproval)

This makes it obvious that the argument is not needed.

Sign up to request clarification or add additional context in comments.

3 Comments

@GP89 Ah, right, it can take >= 1, because the class needs to be passed. Thanks!
That makes it MUCH clearer. But why do we need a classmethod in the firstplace therefore. Couldn't we put just the lambda? Or even better, why not do just: MockUrlRequestPreapproval.preapproval = self.preapproval
I think it's because the rest of the code expects a classmethod. Doing anything else might change the behavior of the class. @cyberjoac
0

cls is just a argument name for lambda ! and you don't use it at all ! lambda cls: self.preapproval) yields a function objec for classmethod ! , As lambda yields a function object you need to use it for pass self.preapproval because of classmethods first argument needs to be a function object !

2 Comments

How would you write this code to be more readable? Why should it be a classmethod and use a lambda in the first place?
as lambda yields a function object you need to use it for pass self.preapproval because of classmethods first argument needs to be a function object !

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.