1. Python / Говнокод #23145

    +2

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    if hasattr(query, "items"):
            query = query.items()
        else:
            # It's a bother at times that strings and string-like objects are
            # sequences.
            try:
                # non-sequence items should not work with len()
                # non-empty strings will fail this
                if len(query) and not isinstance(query[0], tuple):
                    raise TypeError
                # Zero-length sequences of all types will get here and succeed,
                # but that's a minor nit.  Since the original implementation
                # allowed empty dicts that type of behavior probably should be
                # preserved for consistency
            except TypeError:
                ty, va, tb = sys.exc_info()
                raise TypeError("not a valid non-string sequence "
                                "or mapping object").with_traceback(tb)

    https://github.com/python/cpython/blob/master/Lib/urllib/parse.py#L848

    Зачем генерировать TypeError, а потом ее ловить и снова кидать?

    Запостил: Admina_mamu_ebal, 23 Июня 2017

    Комментарии (1) RSS

    • It is not redundant if you want a specific error message. I think that is the point of the code, to indicate the problem to the programmer. So the message is meant to be useful. I can think of three cases:

      >>> urlencode(None) # Non-sequence
      TypeError: not a valid non-string sequence or mapping object
      >>> urlencode({'sized but not indexable'})
      TypeError: not a valid non-string sequence or mapping object
      >>> urlencode('item [0] not a tuple')
      TypeError: not a valid non-string sequence or mapping object

      Официальный ответ с багтрекера.
      Если query не итерируемо или не индексируемо, то TypeError будет брошен ещё в проверке условия, а нужно вывести кастомное сообщение об ошибке, поэтому сделано так.
      Ответить

    Добавить комментарий