- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 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, а потом ее ловить и снова кидать?
PashaWNN 10.12.2018 07:42 # 0
>>> 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 будет брошен ещё в проверке условия, а нужно вывести кастомное сообщение об ошибке, поэтому сделано так.