micropython-lib icon indicating copy to clipboard operation
micropython-lib copied to clipboard

Unreachable and weird code

Open Tangerino opened this issue 1 year ago • 3 comments

In the following snippet we have

            if parse_headers is False:
                pass
            elif parse_headers is True:
                l = str(l, "utf-8")
                k, v = l.split(":", 1)
                resp_d[k] = v.strip()
            else:
                parse_headers(l, resp_d)

The else part is unreachable and at the same time a call to parse_headers is used. parse_headers is not a function.

Tangerino avatar Apr 20 '23 10:04 Tangerino

Update: This is for requests library

Tangerino avatar Apr 20 '23 11:04 Tangerino

While it might seem non-intuitive, this code does actually work such that parse_headers is a multi-purpose argument.

The intention is for library users to pass in:

  • parse_headers=False for no handling
  • parse_headers=True for default handling
  • parse_headers=my_func for custom handling

Importantly, is True only matches for the actual True object, not for any other "True like" things.

If you're unsure, try the test function below:

MicroPython v1.19.1-782-g699477d12 on 2023-01-11; linux [GCC 12.2.0] version
Use Ctrl-D to exit, Ctrl-E for paste mode
>>>
>>> def test(a):
...     if a is False:
...       print("F")
...     elif a is True:
...       print("T")
...     else:
...       print("O")
...
>>> test(True)
T
>>> test(False)
F
>>> test(1)
O
>>>

andrewleech avatar Apr 20 '23 13:04 andrewleech

Did you try a simple code refactoring?

            if not isinstance(parse_headers, bool) :
                parse_headers(l, resp_d)
            elif parse_headers is True:
                l = str(l, "utf-8")
                k, v = l.split(":", 1)
                resp_d[k] = v.strip()

massimosala avatar Jun 01 '23 16:06 massimosala