Page 170 -
P. 170
significance of the pickle
print(‘Pickling error: ‘ + str(perr))
Here’s a snippet of your code as it currently stands. You were to grab
your pencil and strike out the code you no longer need, and then
Import “pickle” near replace it with code that uses the facilities pickle instead. You
the top of your were also to add any additional code that you think you might need.
program.
import pickle Change the access mode to
be “writeable, binary”.
‘wb'
try: 'wb'
with open('man_data.txt', 'w') as man_file, open('other_data.txt', 'w') as other_file:
nester.print_lol(man, fh=man_file) pickle.dump(man, man_file)
nester.print_lol(other, fh=other_file) pickle.dump(other, other_file)
except IOError as err:
print('File error: ' + str(err)) Replace the two calls to “nester.print_lol()”
except pickle.PickleError as perr: with calls to “pickle.dump()”.
print('Pickling error: ' + str(perr))
Don’t forget to handle any exceptions
that can occur.
Q: When you invoked print_lol() earlier, you provided only two arguments, even though the function signature requires you to
provide four. How is this possible?
A: When you invoke a Python function in your code, you have options, especially when the function provides default values for some
arguments. If you use positional arguments, the position of the argument in your function invocation dictates what data is assigned to which
argument. When the function has arguments that also provide default values, you do not need to always worry about positional arguments
being assigned values.
Q: OK, you’ve completely lost me. Can you explain?
A: Consider print(), which has this signature: print(value, sep=' ', end='\n', file=sys.stdout). By
default, this BIF displays to standard output (the screen), because it has an argument called file with a default value of sys.stdout.
The file argument is the fourth positional argument. However, when you want to send data to something other than the screen, you do not need
to (nor want to have to) include values for the second and third positional arguments. They have default values anyway, so you need to provide
values for them only if the defaults are not what you want. If all you want to do is to send data to a file, you invoke the print() BIF like this:
print("Dead Parrot Sketch", file='myfavmonty.txt') and the fourth positional argument uses the value
you specify, while the other positional arguments use their defaults. In Python, not only do the BIFs work this way, but your custom functions
support this mechamism, too.
134 Chapter 4