What is wrong with defining constants as lambdas?

One need not look far to find a solution to Yacht that uses lambdas for constants (e.g.). I have heard at least one pythonista express their displeasure at this. I do not necessarily disagree, but I do wonder: why?

Why should one not define constants as lambdas in Python?

Some thoughts on expected answers (hoping for others):

  • «PEP 8 says one shouldn’t assign a lambda to an identifier»
    This is a weak argument. First, this is an appeal to authority, but the authority itself neglects to offer any reasoning. Second, PEP 8 is like the Pirates’ Code.
  • «Doing so is unpythonic»
    I tentatively agree! However, this answer is very incomplete. Why is it unpythonic? How did it become so? Should it remain so? And of course: why should I care about idiomaticity in this case?
1 Like

Linters and guidance are there to provide style guidance. Style is subjective. Though there’s often general consensus about “good” style and “bad” style. Is wearing clashing colored shirt and pants good style or bad? Who’s to say.

The lambda syntax provides an anonymous. There’s “standard” syntax for creating a named function.

def name(args):
    ...

I’ve seen code where the “regular” function syntax was not used and lambda functions preferred instead pretty widely. It hurts to read. Compare below.

class Foo:
    def __init__(self):
        self.count = 0

    def add(self, val):
        self.count += val

    def get_count(self):
        return self.count

    def get_double(self):
        return self.count * 2


class Bar:
    def __init__(self):
        self.count = 0

    def add(self, val):
        self.count += val

    get_count = lambda x: x.count
    get_double = lambda x: x.count * 2