What is the advantage of the new print function in Python 3.x over the Python 2 print statement?

后端 未结 5 1700
感动是毒
感动是毒 2020-12-05 22:15

I\'ve heard several times that print being a function (3.x) is better than it being a statement (2.x). But why?

I was a fan of it being a statement mainly because it

5条回答
  •  情书的邮戳
    2020-12-05 22:50

    You can replace the built-in print by a custom one:

    import os
    import sys
    
    def print(s):
       sys.stderr.write('Will now print ' + str(s) + '.' + os.linesep)
       sys.stdout.write(str(s) + os.linesep)
    
    print(['A', 'list'])
    # Output: 
    # stderr: Will now print ['A', 'list'].
    # stdout: ['A', 'list']
    

    You can use print inside a lambda or a function call etc.:

    example_timeout_function(call=lambda: print('Hello world'), timeout=5)
    do_things(print_function=print)
    

提交回复
热议问题