它是 Pythonic:命名 lambdas [英] Is it pythonic: naming lambdas

查看:13
本文介绍了它是 Pythonic:命名 lambdas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始欣赏 lambda 表达式在 Python 中的价值,尤其是在函数式编程方面,map返回函数的函数等.不过,我也一直在函数内命名 lambdas,因为:

I'm beginning to appreciate the value of lambda expressions in python, particularly when it comes to functional programming, map, functions returning functions, etc. However, I've also been naming lambdas within functions because:

  • 我多次需要相同的功能并且不想重复代码.
  • 功能特定于它出现的功能;其他地方不需要它.

当我遇到满足上述条件的情况时,我一直在编写一个命名的 lambda 表达式,以便 DRY 和缩小范围的功能.例如,我正在编写一个对某些 numpy 数组进行操作的函数,我需要对传递给该函数的所有数组进行一些适度繁琐的索引(可以很容易地放在一行中).我编写了一个命名的 lambda 表达式来进行索引,而不是编写一个完整的其他函数或在整个函数定义中多次复制/粘贴索引.

When I encounter a situation that meets the above criteria, I've been writing a named lambda expression in order to DRY and narrowly scope functionality. For example, I am writing a function that operates on some numpy arrays, and I need to do some moderately tedious indexing of all the arrays passed to the function (which can easily fit on a single line). I've written a named lambda expression to do the indexing instead of writing a whole other function or copy/pasting the indexing several times throughout the function definition.

def fcn_operating_on_arrays(array0, array1):
    indexer = lambda a0, a1, idx: a0[idx] + a1[idx]
    
    # codecodecode
    
    indexed = indexer(array0, array1, indices)
    
    # codecodecode in which other arrays are created and require `indexer`
    
    return the_answer

这是对python lambdas的滥用吗?我应该把它搞定并定义一个单独的函数吗?

Is this an abuse of python's lambdas? Should I just suck it up and define a separate function?

可能值得链接函数内的函数.

推荐答案

这不是 Pythonic 和 PEP8 不鼓励这样做:

This is not Pythonic and PEP8 discourages it:

总是使用 def 语句而不是赋值语句将 lambda 表达式直接绑定到标识符.

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

是:

def f(x): return 2*x

否:

f = lambda x: 2*x

第一种形式表示生成的函数对象的名称是特别是 'f' 而不是通用的 ''.这是更多一般用于回溯和字符串表示.使用赋值语句消除了 lambda 的唯一好处表达式可以提供一个显式的 def 语句(即它可以嵌入到更大的表达式中)

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)

对此的经验法则是考虑其定义: lambdas 表达式是匿名函数.如果你给它命名,它就不再是匿名的了.:)

A rule of thumb for this is to think on its definition: lambdas expressions are anonymous functions. If you name it, it isn't anonymous anymore. :)

这篇关于它是 Pythonic:命名 lambdas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆