Python 2's print vs Python 3's print()
The syntax for print()
changed between Python 2 and 3. In Python 2, print
was a statement. In Python 3, it has been changed to a built-in function. By changing it to a function, it is now easier to have parameters such as sep
and end
. You can also now use dependency injection techniques like you could with other functions:
def download(url, log=print):
log(f'Downloading {url}')
# ...
def silence(*args):
pass # Do not print anything
download('/js/app.js', log=silence)
# ... or
download('/js/app.js', lambda msg: print('[INFO]', msg))
00:00
In the previous lesson, I spoke about custom data types. In this one, I’m going to drill down a little bit on the differences between print
in Python 2 and Python 3. print()
is one of the more obvious changes between Python 2 and 3. In Python 2, print
was a statement.
00:16
This means you called it without brackets. In order to implement the equivalent functionality of the sep
, end
, and flush
mechanisms that are in the Python 3 arguments, the Python 2 print
had to do some magic stuff and change the syntax a little bit. By changing print()
into a function, it now behaves like the other built-in functions in the system.
00:38
This allows you to get rid of all that special syntax, and you can do things like injection and composition and mocking on the print()
function as if it were any other function—built-in or otherwise. Functions are first class citizens in Python—they can be passed by reference just like any other object. You can see that in this code.
01:00
In this download method, the log
argument is being passed the print()
function by default. If the programmer calls download()
without passing anything additional in, the log()
function will just be the print()
function.
01:15
The silence()
function is an empty function. You can now call download()
with silence()
or print()
. You could not implement this in Python 2 the same way.
01:26
You can also use lambdas, which are anonymous functions inside of Python. This allows you to create print()
passing in specific things like a prefix that says '[INFO]'
, changing the behavior of how the reference function log()
gets called inside of the download()
method. Python also has a pretty print method, which is useful for displaying objects such as dictionaries. In the next lesson, I’ll show you how.
Become a Member to join the conversation.
mrc06405j on Feb. 12, 2021
This lesson uses python object concepts and syntax which has not been covered in previous courses in the “Introduction to Python” course. A lesson on object concepts, Methods and Attributes should be inserted early on in the course.