-2
\$\begingroup\$

Any typing, or other improvements that you could make for this simple function?

def get_json_parsed_from(url: Union[str, bytes]) -> Dict[Any, Any]:
    """Gets a JSON file and returns it parsed, or returns an empty dict if any error occurred."""
    try:
        headers = random_headers()
        headers['Accept'] = 'application/json,text/*;q=0.99'
        return dict(requests.get(url, headers=random_headers()).json())
    except BaseException:
        _LOGGER.exception('Failed getting JSON from %s', repr(url), exc_info=False)
        return {}
\$\endgroup\$
1
  • \$\begingroup\$ Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. \$\endgroup\$
    – Vogel612
    Commented Mar 10, 2019 at 22:06

1 Answer 1

2
\$\begingroup\$
headers = random_headers()
headers['Accept'] = 'application/json,text/*;q=0.99'   
return dict(requests.get(url, headers=random_headers()).json())
  • You are not using headers. You create it and adding the Accept key to it, but then passing a new call to random_headers() to .get instead of using headers.

  • requests.get(...).json() already returns a dict. Passing it to dict(...) is superfluous.

This should be your code:

headers = random_headers()
headers['Accept'] = 'application/json,text/*;q=0.99'   
return requests.get(url, headers=headers).json()
\$\endgroup\$
5
  • \$\begingroup\$ You know what's strange? When I don't surround it with dict(), mypy complains that warning: Returning Any from function declared to return "Dict[Any, Any]". Is this mypy being wrong? Also, if I look up the method definition of .json() in PyCharm, I see def json(self, **kwargs: Any) -> Any. It says it returns Any. \$\endgroup\$ Commented Mar 10, 2019 at 11:44
  • \$\begingroup\$ Wow, good spotting on the headers issue! You're a freaking genius! Thank you! \$\endgroup\$ Commented Mar 10, 2019 at 11:46
  • 1
    \$\begingroup\$ It tells you that because JSON could be an object (dict), array (list) or a primitive (str, float, int, ...). \$\endgroup\$
    – jonrsharpe
    Commented Mar 10, 2019 at 17:42
  • \$\begingroup\$ I updated the function from the code review question, still taking into consideration that json() can return other stuff than dict. Is that good now? \$\endgroup\$ Commented Mar 10, 2019 at 22:05
  • \$\begingroup\$ @jonrsharpe so then, in the function signature I should have -> Any:, right? \$\endgroup\$ Commented Mar 16, 2019 at 7:45

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.