← 输入框|github.com|刷新
Skip to content

support .format for bytes #48232

Closed
Closed

Description

@benjaminp
BPO 3982
Nosy @loewis, @warsaw, @brettcannon, @terryjreedy, @gpshead, @ncoghlan, @pitrou, @vstinner, @ericvsmith, @tiran, @benjaminp, @glyph, @ezio-melotti, @florentx, @vadmium, @serhiy-storchaka
Files
  • byte_format.py: Imitate str.format with bytes function
  • Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

    Show more details

    GitHub fields:

    assignee = None
    closed_at = <Date 2014-07-26.07:00:02.695>
    created_at = <Date 2008-09-27.15:50:40.624>
    labels = ['interpreter-core', 'type-feature']
    title = 'support .format for bytes'
    updated_at = <Date 2016-06-10.22:00:08.951>
    user = 'https://github.com/benjaminp'

    bugs.python.org fields:

    activity = <Date 2016-06-10.22:00:08.951>
    actor = 'ncoghlan'
    assignee = 'none'
    closed = True
    closed_date = <Date 2014-07-26.07:00:02.695>
    closer = 'ncoghlan'
    components = ['Interpreter Core']
    creation = <Date 2008-09-27.15:50:40.624>
    creator = 'benjamin.peterson'
    dependencies = []
    files = ['32009']
    hgrepos = []
    issue_num = 3982
    keywords = []
    message_count = 95.0
    messages = ['73931', '73935', '73936', '73937', '73938', '73939', '74019', '74021', '74022', '74050', '84121', '84123', '90421', '90423', '90425', '90428', '127210', '130215', '130253', '130284', '163369', '163379', '171791', '171795', '171796', '171799', '171800', '171801', '171803', '171804', '171806', '171815', '171816', '171821', '171824', '180414', '180415', '180416', '180419', '180420', '180423', '180426', '180427', '180430', '180431', '180432', '180433', '180436', '180437', '180439', '180441', '180442', '180445', '180446', '180447', '180448', '180449', '180452', '180453', '180454', '180466', '180489', '180490', '180491', '180492', '180493', '180500', '198112', '199181', '199199', '199203', '199204', '199206', '199207', '199251', '199253', '199254', '199258', '199260', '199264', '199265', '199266', '199267', '199268', '199270', '199271', '199432', '199438', '223976', '223979', '224022', '224023', '266568', '268157', '268160']
    nosy_count = 26.0
    nosy_names = ['loewis', 'barry', 'brett.cannon', 'terry.reedy', 'gregory.p.smith', 'exarkun', 'ncoghlan', 'pitrou', 'vstinner', 'eric.smith', 'christian.heimes', 'benjamin.peterson', 'glyph', 'ezio.melotti', 'durin42', 'Arfrever', 'arjennienhuis', 'flox', 'ecir.hana', 'uau', 'tshepang', 'underrun', 'martin.panter', 'serhiy.storchaka', 'nlevitt@gmail.com', 'stendec']
    pr_nums = []
    priority = 'normal'
    resolution = 'wont fix'
    stage = 'resolved'
    status = 'closed'
    superseder = None
    type = 'enhancement'
    url = 'https://bugs.python.org/issue3982'
    versions = ['Python 3.5']

    Activity

    1. benjaminp commented on Sep 27, 2008

      @benjaminp
      ContributorAuthor

      I just working on porting some networking code from 2.x to 3.x and it
      heavily uses string formatting. Since bytes don't support any kind of
      formatting, it's becoming tedious and inelegant to do it with "+". Can
      .format be supported in bytes?

      [I understand format is implemented with stringlib so shouldn't it be
      fairly easy to implement?]

    2. added
      interpreter-core
      type-feature
      on Sep 27, 2008
    3. ericvsmith commented on Sep 27, 2008

      @ericvsmith
      Member

      Yes, it would be easy to add. Maybe bring this up on python-dev (or
      python-3000) to get consensus?

      Are we in feature freeze for 3.0?

    4. benjaminp commented on Sep 27, 2008

      @benjaminp
      ContributorAuthor

      On Sat, Sep 27, 2008 at 12:33 PM, Eric Smith <report@bugs.python.org> wrote:

      Eric Smith <eric@trueblade.com> added the comment:

      Yes, it would be easy to add. Maybe bring this up on python-dev (or
      python-3000) to get consensus?

      Yes, that will have to be done.

      Are we in feature freeze for 3.0?

      Unfortunately, yes.

    5. loewis commented on Sep 27, 2008

      loewismannequin
      Mannequin

      I'm skeptical. What networking code specifically are you using, and what
      specifically does it use string formatting for?

    6. benjaminp commented on Sep 27, 2008

      @benjaminp
      ContributorAuthor

      On Sat, Sep 27, 2008 at 12:35 PM, Martin v. Löwis
      <report@bugs.python.org> wrote:

      Martin v. Löwis <martin@v.loewis.de> added the comment:

      I'm skeptical. What networking code specifically are you using, and what
      specifically does it use string formatting for?

      I'm working on the tests for ftplib. [1] The dummy server uses string
      formatting to build responses.

      [1] http://svn.python.org/view/python/trunk/Lib/test/test_ftplib.py?view=markup

    7. loewis commented on Sep 27, 2008

      loewismannequin
      Mannequin

      I'm working on the tests for ftplib. [1] The dummy server uses string
      formatting to build responses.

      I see. I propose to add a method push_string, defined as

        def push_string(self, s):
            self.push(s.encode("ascii")

      In FTP, the responses are, by definition, ASCII-encoded strings.
      The proper way to generate them is to make a string, then encode it.

    8. vstinner commented on Sep 29, 2008

      @vstinner
      Member

      I don't think that b'...'.format() is a good idea. Programmers will
      continue to mix characters and bytes since .format() target are
      characters.

    9. ericvsmith commented on Sep 29, 2008

      @ericvsmith
      Member

      I don't think that b'...'.format() is a good idea. Programmers
      will continue to mix characters and bytes since .format() target
      are characters.

      b''.format() would return bytes, not a string. This is also how it works
      in 2.6.

      I'm also not sold on implementing it, although it would be easy and I
      can see a few uses for it. I think Martin's suggesting of encoding back
      to ascii might be the best thing to do (that is, don't implement
      b''.format()).

    10. vstinner commented on Sep 29, 2008

      @vstinner
      Member

      I think Martin's suggesting of encoding back to ascii might be
      the best thing to do

      As I understand, you would like to use bytes as characters, like
      b'{code} {message}'.format(code=100, message='OK'). So why no using
      explicit conversion to ASCII? ftp='{code} {message}'.format(code=100,
      message='OK').encode('ASCII').

      If you need to work on bytes, it means that you will use the full
      range 0..255 whereas ASCII reject bytes in 128..255.

    11. loewis commented on Sep 29, 2008

      loewismannequin
      Mannequin

      > I think Martin's suggesting of encoding back to ascii might be
      > the best thing to do

      As I understand, you would like to use bytes as characters, like
      b'{code} {message}'.format(code=100, message='OK'). So why no using
      explicit conversion to ASCII? ftp='{code} {message}'.format(code=100,
      message='OK').encode('ASCII').

      That's indeed exactly what I had proposed - only that you shouldn't
      repeat the .encode('ascii') all over the place, but instead wrap that
      into a function (which I proposed to call push_string, along with the
      existing .push function.

    12. vstinner commented on Mar 24, 2009

      @vstinner
      Member

      loewis> That's indeed exactly what I had proposed
      loewis> - only that you shouldn't repeat the .encode('ascii')
      loewis> all over the place, (...)

      If you can only use bytes 0..127, it can not used for binary protocols
      and so I don't think that it's really useful. If your protocol is
      ASCII text, use explicit conversion to ASCII.

      I also not fan on functions having different result type
      (format->bytes or str, it depends...).

    13. ericvsmith commented on Mar 24, 2009

      @ericvsmith
      Member

      I also not fan on functions having different result type
      (format->bytes or str, it depends...).

      In 3.x, str.format() and bytes.format() would be two different methods
      on two different objects. I don't think there's any expectation that
      they have the same return type. There's no such expectation for
      str.strip() and bytes.strip() either.

      Similarly, in 2.6, str.format() has a different return type than
      unicode.format().

      Now the builtin format() function is another issue. In 2.6 the return
      type does depend on the types of the arguments. In 3.x, I'd suggest
      leaving it as unicode and you won't be allowed to pass in bytes.

    14. arjennienhuis commented on Jul 11, 2009

      arjennienhuismannequin
      Mannequin

      There are many binary formats that use ASCII numbers.

      'HTTP chunking' uses ASCII mixed with binary (octets).

      With 2.6 you could write:

      def chunk(block):
          return b'{0:x}\r\n{1}\r\n'.format(len(block), block)

      With 3.0 you'd have to write this:

      def chunk(block):
          return format(len(block), 'x').encode('ascii') + b'\r\n' + block +
      b'\r\n'

      You cannot convert to ascii at the end of the pipeline as there are
      bytes > 127 in the data blocks.

    15. 72 remaining items

    16. durin42 commented on Oct 8, 2013

      durin42mannequin
      Mannequin

      On Oct 8, 2013, at 6:28 PM, "Terry J. Reedy" <report@bugs.python.org> wrote:

      http://www.python.org/dev/peps/pep-0383/
      One point of the pep is round-trip filenames without loss on all systems, which is just what you say you need.

      At a quick skim, likely not good enough, because http://en.wikipedia.org/wiki/Shift_JIS isn't completely ASCII-compatible, and we've got a fair number of users on weird Shift-JIS using platforms.

    17. glyph commented on Oct 8, 2013

      glyphmannequin
      Mannequin

      On Oct 8, 2013, at 3:19 PM, Augie Fackler wrote:

      No, I'm not. In Mercurial, all end-user data is OPAQUE BYTES, and must remain that way.

      The PEP-383 technique for handling file names is completely capable of round-tripping exact bytes, given one encoding for both input and output. You can still handle file names this way internally in Mercurial and not risk disturbing any observable output. You do not need to change that in order to do what Victor suggests.

      We should get together in some other forum and discuss file-name handling though, since you can't actually round-trip "opaque bytes" through a *filesystem* and not disturb your output.

      Ouch. Is there any way to write things to stderr and stdout without decoding and hopelessly breaking user data?

      You can use sys.stdout.buffer.write.

    18. terryjreedy commented on Oct 9, 2013

      @terryjreedy
      Member

      Here is a proof of concept Python function, with a minimal test. It is similar to how str.format could be coded in Python, with re.split and ''.join, except that it does not allow anything before : in the format specification. By default (no format spec given), it copies bytes objects without change. If a format specification *is* given, it does not restrict the object, as this code simply uses builtin format sandwiched between decode and encode.

    19. ezio-melotti commented on Oct 11, 2013

      @ezio-melotti
      Member

      You can use sys.stdout.buffer.write.

      Note that there's no guarantee that sys.stdout.buffer exists, e.g. if sys.stdout has been replaced with a StringIO.

    20. glyph commented on Oct 11, 2013

      glyphmannequin
      Mannequin

      Tempting as it is to reply to the comment about 'buffer' not existing, we're way off topic here. Let's please keep further comments on this bug to issues about a 'format' methods on the 'bytes' object.

    21. underrun commented on Jul 25, 2014

      underrunmannequin
      Mannequin

      First off, +1 for this feature. It's not just for twisted, but anyone doing anything with binary data (storage, compression, encryption and networking for me) with python since 2.6 will very likely have been using .format for building messages. I know I have and obviously others have been doing so as well.

      The advantages of .format to me are:

      • compatible with 2.6 (porting and single code base support easier)
      • ease of composition (the format langauge makes it easy to build complex data structures out of bytes)
      • readability (named fields make complex formats obvious)
      • consistency (manipulating a block of bytes or characters can be done in a similar way)

      Specific comments on the patch supplied by terry.reedy:

      • it doesn't support named fields
      • it doesn't handle padding
      • it doesn't handle nested formats (like '{0:{1}>{2}}'.format(data,pad_char,pad_width)
      • formatting byte strings with a width embedds the repr of the byte string ( bf(b'{:>10}', [b'test']) == b" b'test'" )

      Really this isn't a good way to solve the problem.

      Has a PEP been created for this? If not how can I help make that happen?

      Including this in 3.5 would be so helpful for us low level systems programmers out there who have lots of code using .format for binary interfaces in python 2.6/2.7 already.

      Also, not to add to derailment, but if we're adding a .format for python3 bytes it would be great if .format could pad with the null byte ('\0') which it currently converts to spaces internally (which is strange). Since this unexpected conversion is bad (so padding with null doesn't happen in python2) its more like a bug fix... actually - maybe that's a separate bug to file on the current .format for text...

    22. underrun commented on Jul 25, 2014

      underrunmannequin
      Mannequin

      sorry, terry's patch does handle padding - just with the caveats i listed later. i should have removed that bullet.

    23. terryjreedy commented on Jul 26, 2014

      @terryjreedy
      Member

      http://legacy.python.org/dev/peps/pep-0461/
      adds % formatting for bytes and bytes array.

      Nick, I have the impression that there was a decision to not add bytes.format. Correct? If so, this issue should be closed. If not, what, if anything, has been decided?

    24. ncoghlan commented on Jul 26, 2014

      @ncoghlan
      Contributor

      Right, bytes.format was considered as part of the PEP-461 discussions, and rejected as an operation that only made sense in the text domain: http://www.python.org/dev/peps/pep-0461/#proposed-variations

      With PEP-461 accepted, and PEP-460 withdrawn, that means we won't be adding bytes.format and bytearray.format.

      bpo-20284 covers the implementation of PEP-461.

    25. gpshead commented on May 28, 2016

      @gpshead
      Member

      This came up in the language summit today when discussing twisted. .format() is still not supported on bytes though % is in 3.5.

      realistically it sounded like twisted needs to support python 3.4 for many years so they can't rely on bytes having a .format() method that also works on 2.7 anyways... but assuming .format() is only useful for text may still have been an oversight. (i'll have to go re-read PEP-460 and 461 and discussion before commenting further)

    26. underrun commented on Jun 10, 2016

      underrunmannequin
      Mannequin

      Gregory - I'm glad that you're willing to consider this again. It still is a constant issue for me, and .format with variable width fields in binary protocols is so the right tool for the job. If there is anything I can do to help get this added to 3.6 let me know. The forward/backward compatibility issue is secondary to me to the flexibility gained from having .format available for bytes.

      Also padding with null bytes that don't get converted would be awesome.

    27. ncoghlan commented on Jun 10, 2016

      @ncoghlan
      Contributor

      The core problem with the idea of adding bytes.format to Python 3 is that the real power of str.format actually lies in the extensible __format__ protocol and the associated format() builtin, as those rely heavily on text-specific assumptions.

      I interpreted Amber's comments at the language summit as referring more to our changing tune regarding mod formatting from:

      • mod formatting is deprecated, use brace formatting instead; to
      • they're both fully supported, neither is deprecated; to
      • use brace formatting for text data, mod formatting for binary data

      Folks that followed our original "stop using mod formatting" guidance thus needed to change course when it became our recommended technique for formatting binary data.

      Since we now know format() and __format__ aren't suitable for binary data (PEP-361 originally included it, and it got dropped as we kept finding awkward corner cases), that means any new binary formatting proposal needs to explain:

      • how it compares to existing serialisation techniques (mod-formatting, the struct module, text-formatting+encoding, etc)
      • why it needs to be a builtin method or function rather than a new serialisation module
    28. transferred this issue fromon Apr 10, 2022
    29. sosi-deadeye commented on Jan 16, 2024

      @sosi-deadeye

      I could have sworn that bytes.format had been implemented. When I needed it once, I came to the realization that this method never existed in Python 3.0, but it did in Python 2.7.

      I also remember that bytes.format triggered an error if the input was of data type str.

      Who else has this false memory?
      Is this the Mandela effect?

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Metadata

    Metadata

    Assignees

    No one assigned

      Labels

      interpreter-coretype-feature

      Projects

      No projects

        Milestone

        No milestone

        Relationships

        None yet

        Development

        No branches or pull requests

        Issue actions