341

I get this pep8 warning whenever I use lambda expressions. Are lambda expressions not recommended? If not why?

2
  • 8
    For clarity, the question refers to a message for an automated check in flake8 (flake8.pycqa.org)
    – rakslice
    Oct 31, 2018 at 1:10
  • it's a pity that we're progressively being told that there's one and one only way of doing things, even though in Python that has never been the case. I wonder how that fosters creativity... Nov 15, 2023 at 17:34

8 Answers 8

401

The recommendation in PEP-8 you are running into is:

Always use a def statement instead of an assignment statement that binds a lambda expression directly to a name.

Yes:

def f(x): return 2*x 

No:

f = lambda x: 2*x 

The first form means that the name of the resulting function object is specifically 'f' instead of the generic '<lambda>'. This is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression)

Assigning lambdas to names basically just duplicates the functionality of def - and in general, it's best to do something a single way to avoid confusion and increase clarity.

The legitimate use case for lambda is where you want to use a function without assigning it, e.g:

sorted(players, key=lambda player: player.rank)

In general, the main argument against doing this is that def statements will result in more lines of code. My main response to that would be: yes, and that is fine. Unless you are code golfing, minimising the number of lines isn't something you should be doing: go for clear over short.

23
  • 22
    I don't see how it's worse. The traceback is still going to include the errant line number and source file. One might say "f" whereas the other says "lambda". Maybe the lambda error is easier to scan because it's not a single-character function name, or a poorly-named long name?
    – user67416
    Feb 17, 2015 at 19:08
  • 6
    @g33kz0r Well, sure, if you assume the rest of your code is going to have poor quality, following conventions won't gain you much. In general, no, it's not the end of the world, but it's still a bad idea. Feb 17, 2015 at 20:42
  • 74
    This answer is not very helpful, because when running the suggested approach of using def through the PEP8 checker, you get E704 multiple statements on one line (def), and if you split it into two lines you get E301 expected 1 blank line, found 0 :-/ Feb 20, 2015 at 14:10
  • 5
    I agree it should be split. My points were that a) it is not split in the answer's code above, causing E704, and b) if you split it, you need an ugly blank line above it to avoid E301. Feb 21, 2015 at 2:10
  • 5
    I use lambdas when I want to emphasize a pure function (no side effects), and sometimes I have to use the same function in two places, i.e. groupby and sort together. So I ignore this convention.
    – manu
    Jan 28, 2016 at 21:53
194

Here is the story, I had a simple lambda function which I was using twice.

a = map(lambda x : x + offset, simple_list)
b = map(lambda x : x + offset, another_simple_list)

This is just for the representation, I have faced couple of different versions of this.

Now, to keep things DRY, I start to reuse this common lambda.

f = lambda x : x + offset
a = map(f, simple_list)
b = map(f, another_simple_list)

At this point my code quality checker complains about lambda being a named function so I convert it into a function.

def f(x):
    return x + offset
a = map(f, simple_list)
b = map(f, another_simple_list)

Now the checker complains that a function has to be bounded by one blank line before and after.

def f(x):
    return x + offset

a = map(f, simple_list)
b = map(f, another_simple_list)

Here we have now 6 lines of code instead of original 2 lines with no increase in readability and no increase in being pythonic. At this point the code checker complains about the function not having docstrings.

In my opinion this rule better be avoided and broken when it makes sense, use your judgement.

8
  • 23
    a = [x + offset for x in simple_list]. No need to use map and lambda here.
    – Georgy
    Apr 23, 2018 at 16:39
  • 29
    @Georgy I believe the point was to move the x + offset portion to an abstracted location that can be updated without changing more than one line of code. With list comprehensions as you mentioned, you would still need two lines of code that contained x + offset they would just now be in list comprehensions. In order to pull those out as the author wanted, you would need a def or lambda.
    – Julian
    Nov 3, 2018 at 2:18
  • 2
    @Julian Apart from def and lambda one could also use functools.partial: f = partial(operator.add, offset) and then a = list(map(f, simple_list)).
    – Georgy
    Nov 18, 2018 at 18:33
  • 1
    What about def f(x): return x + offset (i.e., a simple function defined on a single line)? At least with flake8 I do not get complaints about blank lines.
    – DocOc
    Aug 22, 2019 at 10:50
  • 1
    @Julian In some cases you can use a nested comprehension: a, b = [[x + offset for x lst] for lst in (simple_list, another_simple_list)]
    – wjandrea
    Dec 29, 2019 at 21:03
33

Lattyware is absolutely right: Basically PEP-8 wants you to avoid things like

f = lambda x: 2 * x

and instead use

def f(x):
    return 2 * x

However, as addressed in a recent bugreport (Aug 2014), statements such as the following are now compliant:

a.f = lambda x: 2 * x
a["f"] = lambda x: 2 * x

Since my PEP-8 checker doesn't implement this correctly yet, I turned off E731 for the time being.

2
  • 12
    Even when using def, the PEP8 checker complains with E301 expected 1 blank line, found 0, so you then have to add an ugly blank line before it. Feb 20, 2015 at 14:11
  • I don't think it's just against having assignments in lambda. I have no assignments in mine, just True or False return, yet it gives me C3001 (unnecessary-lambda-assignment) has_attribute = lambda x: x["attribute_name"] != 1 and x["attribute_name"] is not None . Looks like a pretty arbitrary stylistic decision.
    – SwissNavy
    Jan 27, 2023 at 11:39
1

I also encountered a situation in which it was even impossible to use a def(ined) function.

class SomeClass(object):
  # pep-8 does not allow this
  f = lambda x: x + 1  # NOQA

  def not_reachable(self, x):
    return x + 1

  @staticmethod
  def also_not_reachable(x):
    return x + 1

  @classmethod
  def also_not_reachable(cls, x):
    return x + 1

  some_mapping = {
      'object1': {'name': "Object 1", 'func': f},
      'object2': {'name': "Object 2", 'func': some_other_func},
  }

In this case, I really wanted to make a mapping which belonged to the class. Some objects in the mapping needed the same function. It would be illogical to put the a named function outside of the class. I have not found a way to refer to a method (staticmethod, classmethod or normal) from inside the class body. SomeClass does not exist yet when the code is run. So referring to it from the class isn't possible either.

8
  • 1
    You could refer to also_not_reachable in the mapping definition as SomeClass.also_not_reachable Sep 26, 2018 at 23:07
  • 5
    I don't know what point you're trying to make here. Every one of your function names is as reachable as f in both 2.7 and 3.5 for me
    – Eric
    Nov 12, 2018 at 3:15
  • Nope, all the functions, except for the lambda function, are not reachable from within the Class body. You'll get a AttributeError: type object 'SomeClass' has no attribute '...' if you try to access one of those function in the some_mapping object.
    – simP
    Jun 26, 2019 at 9:44
  • 3
    @simP all of them are perfectly accessible. The ones with @staticmethod and @classmethod don't need an object, just SomeClass.also_not_reachable (although they need distinctive names). If you need to access them from class methods just use self.also_not_reachable
    – ababak
    Sep 16, 2019 at 11:34
  • 2
    @simP maybe you should rename your *not_reachable methods as not_as_easily_reachable_from_class_definition_as_a_lambda xD Mar 19, 2020 at 14:27
0

The main reason seems to be that using lambda expressions to create new functions decreases code readability over using the def keyword to create those functions. If you have some code, and some functions are created with def and others with lambda, it can get confusing to tell which are functions and which are variables.

In short, the def keyword is meant to be used for creating new functions, and lambda is meant for anonymous functions (i.e. functions not tied to a name). Defining a variable as the result of some lambda expression seems to fly in the face of the intended use case for a lambda expression.

0

I recently encountered very legitimate reason to assign lambda expression directly (as always it CAN be avoided by creating extra code). Basically I needed to read the value of a variable at a later date, but I also need to construct something from it that the interface I use expects to be lazy-evaluated.

#my_module.py
from ... import get_global_config, Other

class Some(Other):

    SOME_MAPPING = { ... }

    def __init__(self, ...):
        some_attr = lambda: SOME_MAPPING[
            get_global_config().some_param
        ]

        ...
        super().__init__(self, some_attr, ...)

When I construct the object the global_config in question may or may not be set/constructed/fully configured, so I need to defer getting the value of the configuration to a moment when it's actually needed.

Under normal circumstances this could be avoided by using properties, however the interface I'm using/inheriting requires me to assign something concrete or a closure of type Callable[[], ...] to a particular attribute, and I didn't really feel like refactoring 1000s of lines of code at the moment.

-1

If you are using mypy then another reason to prefer defs is type safety.

The following code will pass mypy type checks despite the fact it contains a type error:

y = lambda x: x**2
print(y("fred"))

We can make it type-safe using the annotated code below, and now mypy will detect an error as expected.

from typing import Callable

y: Callable[[int], int] = lambda x: x**2
print(y("fred"))

However, this looks a bit unwieldy. Let's compare with the type-safe def alternative below.

def y(x: int) -> int:
   return x**2


print(y("fred"))

Arguable, the the def version is more readable and concise (objectively, although it takes two lines, it has fewer overall characters, and does not require an additional import).

8
  • 1
    Use a different language if you're looking for type safety. If it's not obvious to the coder what the types needed are on this particular function, python will do nothing to ensure its "safety" -- regardless of adding your type hints or not
    – Jon
    Sep 15, 2023 at 15:28
  • 1
    @Jon, you can run static checkers such as mypy to check for type violations. See mypy-lang.org. It is not uncommon to configure a CI pipeline to run mypy checks for Python production code.
    – Peewee 733
    Sep 28, 2023 at 8:04
  • 1
    but that defies the point. All such usages are optional by design, they are not built into the language... You can modify the language to enforce type checking, but that's something else entirely -- that's not python, that's your special tool / process.
    – Jon
    Oct 2, 2023 at 3:04
  • 1
    PEP 484 introduces a full type system for Python. As you say, types are optional. However, if make use of them and you also make use of mypy, then you can automatically detect type errors at "compile"-time. You do not need to use a different programming language; by using mypy you can detect type errors early just as you would with a statically-typed language such as Java. Yes, you don't have to program this way in Python, but if you do want the level of type safety that you get in compiled languages the option is open to you without having to switch languages.
    – Peewee 733
    Oct 5, 2023 at 17:18
  • Again, this defies the point I've been making. Yes, you can change any language to make it behave the way you want. You could modify Java so that it is loosely typed, just as you can modify python to make it strictly typed. But should you? This is a design decision and it is not as if python just "forgot" to implement type checking and they've been too busy to bother implementing it -- they never will, because there are specific benefits to embracing the design paradigms chosen. Use the tool for its intended purpose.
    – Jon
    Oct 6, 2023 at 16:59
-3

This works for me in a class, remove lambda expression and use def instead, changing this...

    def set_every(self, every: int = 1, time_unit: int = TimeUnit.Day):
        every_func = lambda x: "*" if x == 1 else "*/" + str(x)
        if TimeUnit.has_value(time_unit):
            self.month_of_year = "*"
            self.day_of_month = "*" if time_unit != TimeUnit.Day else every_func(every)
            self.day_of_week = "*" if time_unit != TimeUnit.Week else every_func(every)

by this...

    def set_every(self, every: int = 1, time_unit: int = TimeUnit.Day):
        def every_func(x: int) -> str: return "*" if x == 1 else "*/" + str(x)
        if TimeUnit.has_value(time_unit):
            self.month_of_year = "*"
            self.day_of_month = "*" if time_unit != TimeUnit.Day else every_func(every)
            self.day_of_week = "*" if time_unit != TimeUnit.Week else every_func(every)
2
  • Please add further details to expand on your answer, such as working code or documentation citations.
    – Community Bot
    Aug 29, 2021 at 11:18
  • The OP never said his code doesn't work. It's only a warning, since it is a non-standard coding practice Nov 1, 2021 at 15:32

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.