0

I came across this piece of Python code. The precise function is not important. I'm trying to understand how the arguments to the json.dumps call work. It looks (at a guess) like the intent is to use either body or kwargs['body'] depending on which one is non-null, but doesn't the or operator just return a boolean?

import json
from aiohttp import web

def json_response(body='', **kwargs):
    kwargs['body'] = json.dumps(body or kwargs['body']).encode('utf-8')
    kwargs['content_type'] = 'text/json'
    return web.Response(**kwargs)
Peter Swords
  • 489
  • 6
  • 17
  • 1
    No, `or` returns the first true-ish object. – Martijn Pieters Nov 07 '18 at 17:38
  • 3
    That code doesn't make any sense - `kwargs` will never have a `'body'` entry, because there's a separate `body` parameter. – user2357112 Nov 07 '18 at 17:39
  • The expression is otherwise redundant. `kwargs['body']` will **never** exist, because Python would fill the explicit `body` keyword argument, at all times. – Martijn Pieters Nov 07 '18 at 17:41
  • @user2357112 It could be code in a transitional period - changing between `body` being a keyword argument and being slurped up as part of `**kwargs`, refactoring in a backwards-compatible way. Or, you know...it could just be bad code. – wim Nov 07 '18 at 17:42
  • [Source](https://steelkiwi.com/blog/jwt-authorization-python-part-1-practise/). – wim Nov 07 '18 at 17:44

0 Answers0