[issue3243] Support iterable bodies in httplib

Xuanji Li report at bugs.python.org
Tue Nov 30 15:53:51 CET 2010

Xuanji Li <xuanji at gmail.com> added the comment:

I don't fully understand Lib/urllib/request.py either, I just ported it and ran the unittests... it seems like what it does is that if you send an iterator through as 'data' you can't know the length in advance, and rather than let the len(data) raise an exception catlee thought it's better to raise an exception to tell the user exactly why the code failed (ie, because the user sent an iterator and there's no way to meaningfully find the Content-Length of that).

As for the catching exceptions vs using isinstance: I thought about it for a while, I think something like this feels right to me:

  except TypeError:

      if isinstance(data, collections.Iterable):
          for d in t:
          raise TypeError("data should be a bytes-like object or an iterable, got %r" % type(it))

anyway, calling iter(data) is equivalent to calling data.__iter__(), so catching the exception is equivalent to hasattr(data, '__iter__'), which is roughly the same as isinstance(data, collections.Iterable). so we try the most straightforward method (sending everything) then if that fails, data is either an iterator or a wrong type.


Python tracker <report at bugs.python.org>

More information about the Python-bugs-list mailing list