lambda用于实际代码的是什么? [英] what is lambda used for in real code?

查看:63
本文介绍了lambda用于实际代码的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为将最近的lambda线程放入

透视图可能会有用。我想知道什么lambda用于真正的

代码,所以我grepped我的Python Lib目录。以下是我看待的一些内容,根据我如何重写它们(如果可以的话)分类:

*可重写为def语句(< name> = lambda) < args>:< expr>用法)

这些是在不需要lambda时使用的lambda - 一个匿名的

函数是用lambda创建的然后立刻绑定到一个名字。

因为这基本上是def所做的,所以在这里使用lambdas是(恕我直言)傻。


pickletools.py:getpos = lambda :无

def getpos():返回无

tarfile.py:normpath = lambda路径:

os.path.normpath(path) .replace(os.sep," /")

def normpath(path):os.path.normpath(path).replace(os.sep," /")

urllib2.py:H = lambda x:md5.new(x).hexdigest()

def H(x):md5.new(x).hexdigest()

urllib2.py:H = lambda x:sha.new(x).hexdigest()

def H(x):sha.new(x).hexdigest()

*可用现有的可重写函数

主要是代码示例,可以使用运算符模块中可用的

函数,特别是

operator.itemgetter和运算符.attrgetter(2.4中提供)


cgi.py:返回地图(lambda v:v.value,value)

返回地图(operator.attrgetter( ''value''),value)

CGIHTTPServer.py:nobody = 1 + max(map(lambda x:x [2],pwd.getpwall()))

nobody = 1 + max(map(operator.itemgetter(2),pwd.getpwall()))

SimpleXMLRPCServer.py:server.register_function(lambda x,y:x + y,' 'add'')

server.register_function(operator.add,''add'')

SimpleXMLRPCServer.py:server.register_function(lambda x,y:x + y,''添加'')

server.register_function(operator.add,''add'')

sre_constants.py:items.sort(key = lambda a :a [1])

items.sort(key = operator.itemgetter(1))

tarfile.py:返回地图(lambda m:m.name,self.infolist())

返回地图(operator.attrgetter(''name''),self.infolist())

*可重写与列表推导/生成器表达式

地图或过滤器表达式中的Lambdas通常可以替换为适当的列表推导或生成器表达式(在Python 2.3 / 2.4中) )


cgi.py:plist = map(lambda x:x.strip(),line.split('';''))

plist = [x.strip()for x in line.split('';'')

cgi.py:return map(lambda v:v.value,value)

返回[v.value for v in value]

CGIHTTPServer.py:nobody = 1 + max(map(lambda x:x [2],pwd.getpwall()))

nobody = 1 + max(pwd.getpwall()中x的x [2])

glob.py:names = filter(lambda x:x [0]!=' '。'',姓名)

names = [x代表x中的x,如果x [0]!=''。''']

hmac.py:return" ;.join(map(lambda x,y:chr)(ord(x )^ ord(y)),

s1,s2))

return" .join(chr(ord(x)^ ord(y))for x,y in zip(s1,s2))

imaplib.py:l = map(lambda x:''%s:"%s"'''%(x [0],x [1] [0]和

''" "''。join(x [1])或''''),l)

l = [''%s:"%s"''%(x [0], x [1] [0]和''""''。join(x [1])或'''')

for x in l]

inspect.py:suffixes = map(lambda(后缀,模式,mtype):

(-len(后缀),后缀,模式,mtype),

imp。 get_suffixes())

后缀= [(-len(后缀),后缀,模式,mtype)
后缀中的
,模式,imp.get_suffixes中的mtype()

inspect.py:return join(map(lambda o,c = convert,j = join:

strseq(o,c,j),object))

返回join(对象中的o的[strseq(o,convert,join)])

mailcap.py:entries = filter(lambda e,key = key:key in e,entries )

entries = [e for e in entries如果键入e]

poplib.py:digest =''''。join(map(lambda x:'') %02x''%ord(x),digest))

digest =''''。join(''%02x''%ord(x)for x in digest)

pstats.py:如果是行而不是过滤器(lambda x,a =缩写:

x不在a,line.split()中):

if line而不是[x for x in line.split ()如果x不是缩写]:

tabnanny.py:firsts = map(lambda tup:str(tup [0]),w)

firsts = [str (tup [0])for t t in w]

tarfile.py:return map(lambda m:m.name,self.infolist())

return [m self.infolist()中的.name for m

tarfile.py:返回过滤器(lambda m:m.type in REGULAR_TYPES,

self.tarfile.getmembers() )

返回[m表示在self.tarfile.getmembers()中的m。

如果在REGULAR_TYPES中的m.type]

urllib2.py:return map(lambda x:x.strip(),list)

返回[x.strip()for x in list]

webbrowser.py:_tryorder = filter(lambda x:x.lower()in _browsers

或x.find("%s")> -1,_tryorder

_tryorder = [x for _tryorder中的x

如果_browsers中的x.lower()或x.find("%s")> -1]

*功能我不知道如何重写

我看过的一些功能,我无法找到重写它们的方法

,不引入新名称或添加新语句。 (警告:我

在使用''reduce''的代码时遇到问题,因此我只会在减少调用时屏蔽

lambdas。)

calendar.py:_months.insert(0,lambda x:"")

cgitb.py:inspect.formatargvalues(args,varargs,varkw,locals,
formatvalue = lambda值:''=''+ pydoc.html.repr(value))

cgitb.py:inspection.formatargvalues(args,varargs,varkw,locals,

formatvalue = lambda值:''=''+ pydoc.text.repr(value))

csv.py:signchar = reduce(lambda a,b,quotes =引号:

(引号[a]>引号[b])和a或b,quotes.keys())

csv.py:delim = reduce(lambda a,b,delims = delims:

(delims [a]> delims [b])和a或b,delims.keys())

difflib.py :matches = reduce(lambda sum,triple:sum + triple [-1],

self.get_matching_blocks(),0)

gettext.py:return eval(' 'lambda n:int(%s)''%plur al)

gettext.py:self.plural = lambda n:int(n!= 1)

inspect.py:classes.sort(key = lambda c :( c .__ module __,c .__ name__))

inspect.py:def formatargspec(args,varargs = None,varkw = None,

...

formatvarargs = lambda name:''*''+ name,

formatvarkw = lambda name:''**''+ name,

formatvalue = lambda value :''=''+ repr(值),

inspect.py:def formatargvalues(args,varargs,varkw,locals,

......

formatvarargs = lambda name:''*''+ name,

formatvarkw = lambda name:''**''+ name,

formatvalue = lambda value:''=''+ repr(value),

pyclbr.py:objs.sort(lambda a,b:cmp(getattr(a,''lineno'',0),

getattr(b,''lineno'',0)))

SimpleHTTPServer.py:list.sort(key = lambda a:a.lower())

subprocess.py:p = Popen([" id"],preexec_fn = lambda:os.setuid(100))
symtable.py:self .__ params = self .__ idents_matching(lambda x:

x& DEF_PARAM)

symtable.py:self .__ locals = self .__ idents_matching(lambda x:

x& DEF_BOUND)

symtable.py:self .__ globals = self .__ idents_matching(lambda x:

x& glob)

urllib2.py:setattr(self,''%s_open''%type,
lambda r,proxy = url,type = type,meth = self.proxy_open:

meth(r,proxy,type))

xdrlib.py :unpacktest = [

(up.unpack_uint,(),lambda x:x == 9),

(up.unpack_bool,(),lambda x:not x ),

(up.unpack_bool,(),lambda x:x),

(up.unpack_uhyper,(),lambda x:x == 45L),

(up.unpack_float,(),lambda x:1.89< x< 1.91),

(up.unpack_double,(),lambda x:1.89< x < 1.91),

(up.unpack_string,(),lambda x:x ==''hello world''),

(up.unpack_list,(up .unpack_uint,),lambda x:x == range(5)),
(up.unpack_array,(up.unpack_string,),

lambda x:x = = ['什么'',''','''''''''''''''''''''''''''$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
我不知道如何重写,我认为有一些有趣的案例:


(1)lambda x:""

这是一种参数改编,我认为Jeff Shannon在另一个lambda线程中谈论的是
。使用ignoreargs函数我建议在那里使用
[1],你可以将其重写为:

ignoreargs(str,1)

(2) lambda a:a.lower()

我在这里首先想到的是使用str.lower而不是lambda,但是

当然如果'不起作用' 'a''是一个unicode对象:


py> str.lower(u''a'')

Traceback(最近一次调用最后一次):

文件"< interactive input>",第1行,in ?

TypeError:描述符''lower''需要一个''str''对象,但是收到了一个

''unicode''


太糟糕了,我做不了类似的事情:

basestring.lower

(3)self.plural = lambda n:int(n != 1)

请注意,这几乎是*可写的def语法。如果我们能做到:

def self.plural(n):

int(n!= 1)

(4)objs。 sort(lambda a,b:cmp(getattr(a,''lineno'',0),

getattr(b,''lineno'',0)))

我这里的第一个直觉是尝试类似的东西:

objs.sort(key = operator.attrgetter(''lineno''))

但这不是''工作,因为如果该属性不存在,我们不会得到默认值0

。我想知道operator.attrgetter是否应该使用可选的默认作为
。像getattr这样的参数:

模块__builtin__中内置函数getattr的帮助:


getattr(...)

getattr(object,name [,default]) - >价值

(5)lambda x:x& DEF_PARAM

这可能写成:

functional.partial(operator.and_,DEF_PARAM)
如果接受PEP 309 [2]则
,我以为我没有声称'更清楚......


所以,这些是我对lambdas如何真正的看法。用过的。如果其他人

有现实代码以有趣的方式使用lambdas,

可以在这里分享它们!


史蒂夫


[1] http://mail.python.org/pipermail/python-list/2004-December/257982.html

[2 ] http://python.fyxm.net/peps/pep-0309.html

I thought it might be useful to put the recent lambda threads into
perspective a bit. I was wondering what lambda gets used for in "real"
code, so I grepped my Python Lib directory. Here are some of the ones I
looked, classified by how I would rewrite them (if I could):
* Rewritable as def statements (<name> = lambda <args>: <expr> usage)
These are lambdas used when a lambda wasn''t needed -- an anonymous
function was created with lambda and then immediately bound to a name.
Since this is essentially what def does, using lambdas here is (IMHO) silly.

pickletools.py: getpos = lambda: None
def getpos(): return None
tarfile.py: normpath = lambda path:
os.path.normpath(path).replace(os.sep, "/")
def normpath(path): os.path.normpath(path).replace(os.sep, "/")
urllib2.py: H = lambda x: md5.new(x).hexdigest()
def H(x): md5.new(x).hexdigest()
urllib2.py: H = lambda x: sha.new(x).hexdigest()
def H(x): sha.new(x).hexdigest()
* Rewritable with existing functions
Mainly these are examples of code that can benefit from using the
functions available in the operator module, especially
operator.itemgetter and operator.attrgetter (available in 2.4)

cgi.py: return map(lambda v: v.value, value)
return map(operator.attrgetter(''value''), value)
CGIHTTPServer.py: nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
nobody = 1 + max(map(operator.itemgetter(2), pwd.getpwall()))
SimpleXMLRPCServer.py: server.register_function(lambda x,y: x+y, ''add'')
server.register_function(operator.add, ''add'')
SimpleXMLRPCServer.py: server.register_function(lambda x,y: x+y, ''add'')
server.register_function(operator.add, ''add'')
sre_constants.py: items.sort(key=lambda a: a[1])
items.sort(key=operator.itemgetter(1))
tarfile.py: return map(lambda m: m.name, self.infolist())
return map(operator.attrgetter(''name''), self.infolist())
* Rewritable with list comprehensions/generator expressions
Lambdas in map or filter expressions can often be replaced by an
appropriate list comprehension or generator expression (in Python 2.3/2.4)

cgi.py: plist = map(lambda x: x.strip(), line.split('';''))
plist = [x.strip() for x in line.split('';'')
cgi.py: return map(lambda v: v.value, value)
return [v.value for v in value]
CGIHTTPServer.py: nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
nobody = 1 + max(x[2] for x in pwd.getpwall())
glob.py: names=filter(lambda x: x[0]!=''.'',names)
names=[x for x in names if x[0] != ''.'']
hmac.py: return "".join(map(lambda x, y: chr(ord(x) ^ ord(y)),
s1, s2))
return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(s1, s2))
imaplib.py: l = map(lambda x:''%s: "%s"'' % (x[0], x[1][0] and
''" "''.join(x[1]) or ''''), l)
l = [''%s: "%s"'' % (x[0], x[1][0] and ''" "''.join(x[1]) or '''')
for x in l]
inspect.py: suffixes = map(lambda (suffix, mode, mtype):
(-len(suffix), suffix, mode, mtype),
imp.get_suffixes())
suffixes = [(-len(suffix), suffix, mode, mtype)
for suffix, mode, mtype in imp.get_suffixes()
inspect.py: return join(map(lambda o, c=convert, j=join:
strseq(o, c, j), object))
return join([strseq(o, convert, join) for o in object])
mailcap.py: entries = filter(lambda e,key=key: key in e, entries)
entries = [e for e in entries if key in e]
poplib.py: digest = ''''.join(map(lambda x:''%02x''%ord(x), digest))
digest = ''''.join(''%02x'' % ord(x) for x in digest)
pstats.py: if line and not filter(lambda x,a=abbrevs:
x not in a,line.split()):
if line and not [x for x in line.split() if x not in abbrevs]:
tabnanny.py: firsts = map(lambda tup: str(tup[0]), w)
firsts = [str(tup[0]) for tup in w]
tarfile.py: return map(lambda m: m.name, self.infolist())
return [m.name for m in self.infolist()]
tarfile.py: return filter(lambda m: m.type in REGULAR_TYPES,
self.tarfile.getmembers())
return [m for m in self.tarfile.getmembers()
if m.type in REGULAR_TYPES]
urllib2.py: return map(lambda x: x.strip(), list)
return [x.strip() for x in list]
webbrowser.py: _tryorder = filter(lambda x: x.lower() in _browsers
or x.find("%s") > -1, _tryorder
_tryorder = [x for x in _tryorder
if x.lower() in _browsers or x.find("%s") > -1]
* Functions I don''t know how to rewrite
Some functions I looked at, I couldn''t figure out a way to rewrite them
without introducing a new name or adding new statements. (Warning: I
have trouble following code that uses ''reduce'', so I only glossed over
lambdas in reduce calls.)

calendar.py: _months.insert(0, lambda x: "")
cgitb.py: inspect.formatargvalues(args, varargs, varkw, locals,
formatvalue=lambda value: ''='' + pydoc.html.repr(value))
cgitb.py: inspect.formatargvalues(args, varargs, varkw, locals,
formatvalue=lambda value: ''='' + pydoc.text.repr(value))
csv.py: quotechar = reduce(lambda a, b, quotes = quotes:
(quotes[a] > quotes[b]) and a or b, quotes.keys())
csv.py: delim = reduce(lambda a, b, delims = delims:
(delims[a] > delims[b]) and a or b, delims.keys())
difflib.py: matches = reduce(lambda sum, triple: sum + triple[-1],
self.get_matching_blocks(), 0)
gettext.py: return eval(''lambda n: int(%s)'' % plural)
gettext.py: self.plural = lambda n: int(n != 1)
inspect.py: classes.sort(key=lambda c: (c.__module__, c.__name__))
inspect.py: def formatargspec(args, varargs=None, varkw=None,
...
formatvarargs=lambda name: ''*'' + name,
formatvarkw=lambda name: ''**'' + name,
formatvalue=lambda value: ''='' + repr(value),
inspect.py: def formatargvalues(args, varargs, varkw, locals,
...
formatvarargs=lambda name: ''*'' + name,
formatvarkw=lambda name: ''**'' + name,
formatvalue=lambda value: ''='' + repr(value),
pyclbr.py: objs.sort(lambda a, b: cmp(getattr(a, ''lineno'', 0),
getattr(b, ''lineno'', 0)))
SimpleHTTPServer.py: list.sort(key=lambda a: a.lower())
subprocess.py: p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
symtable.py: self.__params = self.__idents_matching(lambda x:
x & DEF_PARAM)
symtable.py: self.__locals = self.__idents_matching(lambda x:
x & DEF_BOUND)
symtable.py: self.__globals = self.__idents_matching(lambda x:
x & glob)
urllib2.py:setattr(self, ''%s_open'' % type,
lambda r, proxy=url, type=type, meth=self.proxy_open:
meth(r, proxy, type))
xdrlib.py: unpacktest = [
(up.unpack_uint, (), lambda x: x == 9),
(up.unpack_bool, (), lambda x: not x),
(up.unpack_bool, (), lambda x: x),
(up.unpack_uhyper, (), lambda x: x == 45L),
(up.unpack_float, (), lambda x: 1.89 < x < 1.91),
(up.unpack_double, (), lambda x: 1.89 < x < 1.91),
(up.unpack_string, (), lambda x: x == ''hello world''),
(up.unpack_list, (up.unpack_uint,), lambda x: x == range(5)),
(up.unpack_array, (up.unpack_string,),
lambda x: x == [''what'', ''is'', ''hapnin'', ''doctor'']),
]

Of the functions that I don''t know how to rewrite, I think there are a
few interesting cases:

(1) lambda x: ""
This is the kind of parameter adaptation that I think Jeff Shannon was
talking about in another lambda thread. Using the ignoreargs function I
suggested there[1], you could rewrite this as:
ignoreargs(str, 1)
(2) lambda a: a.lower()
My first thought here was to use str.lower instead of the lambda, but of
course that doesn''t work if ''a'' is a unicode object:

py> str.lower(u''a'')
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: descriptor ''lower'' requires a ''str'' object but received a
''unicode''

It''s too bad I can''t do something like:
basestring.lower
(3) self.plural = lambda n: int(n != 1)
Note that this is *almost* writable with def syntax. If only we could do:
def self.plural(n):
int(n != 1)
(4) objs.sort(lambda a, b: cmp(getattr(a, ''lineno'', 0),
getattr(b, ''lineno'', 0)))
My first intuition here was to try something like:
objs.sort(key=operator.attrgetter(''lineno''))
but this doesn''t work because then we don''t get the default value of 0
if the attribute doesn''t exist. I wonder if operator.attrgetter should
take an optional "default" parameter like getattr does:
Help on built-in function getattr in module __builtin__:

getattr(...)
getattr(object, name[, default]) -> value
(5) lambda x: x & DEF_PARAM
This could probably be written as:
functional.partial(operator.and_, DEF_PARAM)
if PEP 309[2] was accepted, thought I''m not claiming that''s any clearer...

So, those are my thoughts on how lambdas are "really" used. If others
out there have real-life code that uses lambdas in interesting ways,
feel free to share them here!

Steve

[1]http://mail.python.org/pipermail/python-list/2004-December/257982.html
[2]http://python.fyxm.net/peps/pep-0309.html

推荐答案

Steven Bethard< st ****** ******@gmail.com>写道:
Steven Bethard <st************@gmail.com> wrote:
(2)lambda a:a.lower()
我首先想到的是使用str.lower而不是lambda,但是
如果''a''是unicode对象,那么当然不起作用:


对,但是string.lower有效(在''import string''之后)。更多

一般来说,也许有一种方法可以说在
x上调用方法。没有x'的类型被检查,就像attrgetter说在x上获取一个

属性 - 说s /之类的:


def methodcaller(method_name,* a,** k):

def callit(x):

返回getattr(x,method_name)(* a,** k)

callit .__ name__ = method_name

return callit

(3)self.plural = lambda n:int(n!= 1)
请注意,这几乎是*可写的def语法。如果我们能做到:
def self.plural(n):
int(n!= 1)


不确定上下文,但也许我们可以在班级使用:

@staticmethod

def plural(n):

return int(n!= 1)


(4)objs.sort(lambda a,b:cmp(getattr(a,''lineno'',0),
getattr(b,''lineno'' ,0)))
我在这里的第一个直觉是尝试类似的东西:
objs.sort(key = operator.attrgetter(''lineno''))
但这不是工作,因为如果属性不存在,我们不会得到默认值0
。我想知道operator.attrgetter是否应该采用可选的默认方式。像getattr这样的参数确实:
(2) lambda a: a.lower()
My first thought here was to use str.lower instead of the lambda, but of
course that doesn''t work if ''a'' is a unicode object:
Right, but string.lower works (after an ''import string''). More
generally, maybe it would be nice to have a way to say "call a method on
x" without x''s type being checked, just like attrgetter says "fetch an
attribute on x" -- say s/thing like:

def methodcaller(method_name, *a, **k):
def callit(x):
return getattr(x, method_name)(*a, **k)
callit.__name__ = method_name
return callit

(3) self.plural = lambda n: int(n != 1)
Note that this is *almost* writable with def syntax. If only we could do:
def self.plural(n):
int(n != 1)
Not sure about the context, but maybe we could use, at class-level:
@staticmethod
def plural(n):
return int(n != 1)

(4) objs.sort(lambda a, b: cmp(getattr(a, ''lineno'', 0),
getattr(b, ''lineno'', 0)))
My first intuition here was to try something like:
objs.sort(key=operator.attrgetter(''lineno''))
but this doesn''t work because then we don''t get the default value of 0
if the attribute doesn''t exist. I wonder if operator.attrgetter should
take an optional "default" parameter like getattr does:




可选的默认参数对我来说听起来不错。

即使有很多lambda使用可能通过这种方式可以避免或可移动

,我认为只有一点点变化 - 在一些

的情况下,一个名字的def必须是最好的(就像它今天甚至会b / b
,如果说,if / else必须是逻辑的一部分 - 模拟

三元运算符很少是最清晰的固体)。

Alex



The optional default parameter sounds like a good idea to me.
Even though a good number of lambda uses may be avoidable or removable
by such means, I think there''s just slightly too much variety -- in some
cases, a def with a name will have to be best (just as it would even
today if, say, an if/else had to be part of the logic -- simulations of
ternary operators being rarely clearest and most solid).
Alex


>所以,这些是关于lambdas如何真正的想法。用过的。如果有其他人
> So, those are my thoughts on how lambdas are "really" used. If others
,那么现实代码会以有趣的方式使用lambdas,
随时可以在这里分享!
out there have real-life code that uses lambdas in interesting ways,
feel free to share them here!




我将它们与元类和属性结合使用:


def _s_item(self,item):

""" saw :: active"""

self .__ item = item

self.set_state()

self.indexWidget.setText( "%i"%item.index)

created = item.created

dt = QDateTime(QDate(created.year,created.month,created.day),

QTime(created.hour,created.minute,created.second))

self.createdWidget.setDateTime(dt)

self.set_text ()

self.set_list_items(self.history,item.history)

self.set_list_items(self.trainlog,item.train_log)

self.set_classification_result()


self.adjust_header_sizes()


def _g_item(个体经营):

返回自我.__项目


#延迟绑定需要lambda,以便元类包装将生效。
#生效。

item = property(_g_item,lambda self,v:self._s_item(v))

_s_item的doc字符串包含元类知道的标记和

创建一个围绕_s_item包装。这对方法很有效,但我发现

属性绑定到它们的函数_before_元类踢了

in,所以在包装版本中没有调用该属性,导致

错误。所以我介绍了使方法调用lazy的lambda。

当然我可以介绍一个


def _s_item_unwrapped(self,v):

self._s_item(v)


并且在属性中使用它 - 但是因为有lambdas,我使用它们。


这里的第二个def不是更多解释,因为必须掌握python属性的内部细节,以了解为什么首先引入额外的箍是


- -

问候,


Diez B. Roggisch



I use them in conjunction with metaclasses and properties:

def _s_item(self, item):
""" saw::active """
self.__item = item
self.set_state()
self.indexWidget.setText("%i" % item.index)
created = item.created
dt = QDateTime(QDate(created.year, created.month, created.day),
QTime(created.hour, created.minute,created.second))
self.createdWidget.setDateTime(dt)
self.set_text()
self.set_list_items(self.history, item.history)
self.set_list_items(self.trainlog, item.train_log)
self.set_classification_result()

self.adjust_header_sizes()

def _g_item(self):
return self.__item

# the lambda is needed for late-binding so that metaclass-wrapping will
# be in effect.
item = property(_g_item, lambda self, v: self._s_item(v))
The doc string of _s_item contains a token the metaclass is aware of and
creates a wrapper around _s_item. That works nice on methods, but I found
that properties got bound to their functions _before_ the metaclass kicks
in, so the property wasn''t called in the wrapped version, resulting in
errors. So I introduced the lambda that makes the method call "lazy". Of
course I could have introduced a

def _s_item_unwrapped(self, v):
self._s_item(v)

and used that in the property - but as there are lambdas, I use them :)

And the second def here is not more explanatory, as one has to graps the
internal details of python properties to understand why that extra hoop is
introduced in the first place.
--
Regards,

Diez B. Roggisch


Alex Martelli写道:
Alex Martelli wrote:
Steven Bethard< st ************ @ gmail.com>写道:
Steven Bethard <st************@gmail.com> wrote:
(2)lambda a:a.lower()
我首先想到的是使用str.lower而不是lambda,但是
如果''''是一个unicode对象,那么当然不起作用:

对,但string.lower有效(在''import string''之后)。更多
一般来说,或许有一种说在x上调用方法的方法会很好。没有检查x'的类型,就像attrgetter说在x上获取
属性一样 - 说s /之类的:

def methodcaller(method_name,* a,** k):
def callit(x):
return getattr(x,method_name) (* a,** k)
callit .__ name__ = method_name
return callit
(2) lambda a: a.lower()
My first thought here was to use str.lower instead of the lambda, but of
course that doesn''t work if ''a'' is a unicode object:

Right, but string.lower works (after an ''import string''). More
generally, maybe it would be nice to have a way to say "call a method on
x" without x''s type being checked, just like attrgetter says "fetch an
attribute on x" -- say s/thing like:

def methodcaller(method_name, *a, **k):
def callit(x):
return getattr(x, method_name)(*a, **k)
callit.__name__ = method_name
return callit




是的,那就是那种东西我在寻找。非常好!



Yeah, that''s exactly the kind of thing I was looking for. Very nice!

(3)self.plural = lambda n:int(n!= 1)
请注意,这几乎是* *可以使用def语法编写。如果我们能做的话:
def self.plural(n):
int(n!= 1)
(3) self.plural = lambda n: int(n != 1)
Note that this is *almost* writable with def syntax. If only we could do:
def self.plural(n):
int(n != 1)



不确定上下文,但也许我们可以在班级使用:
@staticmethod
def plural(n):
return int(n!= 1)


Not sure about the context, but maybe we could use, at class-level:
@staticmethod
def plural(n):
return int(n != 1)




上下文属于GNUTranslations的_parse方法。基本上,

这个方法使用传入的fp和一堆条件来确定如何定义复数方法。所以我不认为它可以在班级完成。另外,不是作业:

self.plural = lambda n:int(n!= 1)

使这更像(在班级):< br $>
def复数(self,n):

返回int(n!= 1)

也就是说,这不是一个实例方法,而不是静态方法?


py> C类(对象):

.... def __init __(自我):

.... self.plural = lambda n:int(n!= 1)

....

py> c = C()

py> c .__ class __ .multiple(1)

Traceback(最近一次调用最后一次):

文件"< interactive input>",第1行,in?

AttributeError:type object''C''没有属性''复数''

py> c.plural(1)

0

尽管通过这种方式可以避免或可移除大量的lambda使用,我认为有只是有点太多的变化 - 在某些情况下,带名字的def必须是最好的



The context was within the _parse method of GNUTranslations. Basically,
this method uses the fp passed in and a bunch of conditionals to
determine how to define the plural method. So I don''t think it can be
done at the class level. Also, doesn''t the assignment:
self.plural = lambda n: int(n != 1)
make this more like (at class level):
def plural(self, n):
return int(n != 1)
that is, isn''t this an instance method, not a staticmethod?

py> class C(object):
.... def __init__(self):
.... self.plural = lambda n: int(n != 1)
....
py> c = C()
py> c.__class__.plural(1)
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
AttributeError: type object ''C'' has no attribute ''plural''
py> c.plural(1)
0
Even though a good number of lambda uses may be avoidable or removable
by such means, I think there''s just slightly too much variety -- in some
cases, a def with a name will have to be best




是的,这是我的感觉。我只能用一个表达式重写

我发现的大约50%的lambda。但是,我(个人)不会在大多数其他情况下添加def有很多问题。

唯一让我有点儿的人紧张的例子如下:


inspect.py:def formatargspec(args,varargs = None,varkw = None,

...

formatvarargs = lambda name:''*''+ name,

formatvarkw = lambda name:''**''+ name,

formatvalue = lambda value :''=''+ repr(value),


其中lambdas在def中声明函数作为关键字参数。

我不是确定我有多喜欢向模块中添加多个函数

defs真的只能在formatargspec中访问。

仍然,lambda在Python 3000中消失了,它肯定不会是世界末日的价值.-)


史蒂夫



Yup, that was my feeling. I was only able to rewrite as an expression
about 50% of the lambdas that I found. However, I (personally) don''t
have much of a problem with adding a def in most of the other cases.
The only ones that make me a little nervous are examples like:

inspect.py: def formatargspec(args, varargs=None, varkw=None,
...
formatvarargs=lambda name: ''*'' + name,
formatvarkw=lambda name: ''**'' + name,
formatvalue=lambda value: ''='' + repr(value),

where the lambdas are declaring functions as keyword arguments in a def.
I''m not sure how much I like adding to the module multiple function
defs that are really intended to be accessed only within formatargspec.
Still, were lambda to go away in Python 3000, it certainly wouldn''t be
the end of the world. ;-)

Steve


这篇关于lambda用于实际代码的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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