2017-09-26 57 views
0

在我的函数中,如果存在一个字典(作为参数传入),则添加另一个字典,否则将其用作字典。 (在此情况下是相关的字典)这种使用python三元运算符失败 - 不知道为什么?

def some_view(request, form_class, template, success_url, context=None): 
    .......... 
    if context is not None: 
     context.update({'form': form}) 
    else: 
     context = {'form': form} 
    return render(request, template, context) 

这工作得很好,但使用

context = context.update({'form': form}) if context is not None else {'form': form} 

由于某种原因失败的情况下是回报率无?

+0

如果'context'是没有,你怎么能叫'update'上呢? – schwobaseggl

+6

'context.update()'返回'None',但你在分配中使用它 – CoryKramer

+0

这是因为当你用python更新字典时,它不会返回任何东西。更新发生在原地。 – rrawat

回答

4

你正在寻找成语简直是

if context is None: 
    context = {} 
context.update({'form': form}) 
+2

'context = context或{}'更短(即使不完全相同)。 – schwobaseggl

+1

我更喜欢明确。 – chepner

+0

是的,看起来像最好的方式,谢谢。 – Yunti