2017-09-26 32 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

相關問題