print() vs sys.stdout.write(): which and why?

后端 未结 1 1398
别那么骄傲
别那么骄傲 2021-01-30 17:05

I have a script that creates output with sys.stdout.write() and sys.stderr.write(). Recently I\'ve posted a couple questions about other aspects of the

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 17:36

    "Can someone please explain (or direct me to an existing explanation) the differences between print() and sys.stdout.write, the cases in which each should be used and the rational for those conventions?"

    Well I guess the silence you hear regarding Python3's print() function, is because there practically is only one difference: Usage. Let me quote PEP-3105: [1]

    The signature for print() is:

    def print(*args, sep=' ', end='\n', file=None)

    A call like:

    print(a, b, c, file=sys.stderr)

    will be equivalent to today's:

    print >>sys.stderr, a, b, c

    while the optional sep and end arguments specify what is printed between and after the arguments, respectively.

    The softspace feature (a semi-secret attribute on files currently used to tell print whether to insert a space before the first item) will be removed. Therefore, there will not be a direct translation for today's:

    print "a", print

    which will not print a space between the "a" and the newline.

    So, quoting Guido van Rossum's discussion of the problem in 2005 [1]: There is a distinct non-linearity in print's ease of use once you decide that you don't want to have spaces between items; you either have to switch to using sys.stdout.write(), or you have to collect all items in a string. This is not a simple transformation, consider what it takes to get rid of the spaces before the commas in this simple example:

    print "x =", x, ", y =", y, ", z =", z
    

    If it was a built-in function, having a built-in companion function that did a similar thing without inserting spaces and adding a newline would be the logical thing to do (or adding keyword parameters to control that behavior; but I prefer a second function); but with only print as it currently stands, you'd have to switch to something like

    print "x = " + str(x) + ", y = " + str(x) + ", z = " + str(z)
    

    or

    print "x = %s, y = %s, z = %s" % (x, y, z)
    

    neither of which is very attractive. (And don't tell me that the spaces are no big deal -- they aren't in this example, but they are in other situations.)


    Good question for a sunday morning down memory lane; Why this apparent redundancy? Because it is pythonically more correct to write higher-level code:

    7th Zen of python: "Readability counts"

    0 讨论(0)
提交回复
热议问题