0

In my function, if a dictionary exists (passed in as a parameter) then add another dictionary to it, or else use it as the dictionary. (here context is the relevant dictionary)

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)

This works fine but using

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

fails for some reason as context is return as None?

4
  • If context is None, how can you call update on it? Commented Sep 26, 2017 at 13:57
  • 6
    context.update() returns None but you're using it in an assignment Commented Sep 26, 2017 at 13:57
  • This is because when you update an dictionary in python, it does not return anything. The update happens inplace. Commented Sep 26, 2017 at 14:00
  • Thanks that's the issue, it updated in place so doesn't return anything, so can't be used for an assignment. I was thinking of it like evaluating an expression, so context could be assigned to it. Commented Sep 26, 2017 at 14:13

1 Answer 1

4

The idiom you are looking for is simply

if context is None:
    context = {}
context.update({'form': form})
Sign up to request clarification or add additional context in comments.

2 Comments

context = context or {} is even shorter (even though not exactly the same).
I prefer to be explicit.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.