On Sat, Feb 11, 2023 at 08:30:22AM +1100, Chris Angelico wrote: > On Sat, 11 Feb 2023 at 07:36, Python <pyt...@bladeshadow.org> wrote: > > You would do this instead: > > > > message = f"{username} has the occupation {job}." > > message_length = len(message) > > print(message) > > print(message_length) > > ... > > > > It's worth noting WHY output functions often return a byte count. It's > primarily for use with nonblocking I/O, with something like this: > > buffer = b".............." > buffer = buffer[os.write(fd, buffer):] > > It's extremely important to be able to do this sort of thing, but not > with the print function, which has a quite different job.
I would agree with this only partially. Your case applies to os.write(), which is essentially just a wrapper around the write() system call, which has that sort of property... though it applies also to I/O in blocking mode, particularly on network sockets, where the number of bytes you asked to write (or read) may not all have been transferred, necessitating trying in a loop. However, Python's print() function is more analogous to C's printf(), which returns the number of characters converted for an entirely different reason... It's precisely so that you'll know what the length of the string that was converted is. This is most useful with the *snprintf() variants where you're actually concerned about overrunning the buffer you've provided for the output string, so you can realloc() the buffer if it was indeed too small, but it is also useful in the context of, say, a routine to format text according to the size of your terminal. In that context it really has nothing to do with blocking I/O or socket behavior. -- https://mail.python.org/mailman/listinfo/python-list