ITFdn100 A - Autumn 2017 - On exception handling, and pickling, in Python

Hi folks,

This post is for Assignment07 in IntroToProg-Python, with Instructor Randal Root.


So, I'd had some previous (minimal) experience with Python try/except blocks. For this course, though, per the instructions for this assignment, I went on the Internet to find some examples of Python exception handling.

First, I searched "Python 3 try except" on DuckDuckGo (DDG). I found several results from python dot org, but chose to look closer at a result from stack overflow - Python exceptions.

User question:


Different user's answer:



And a new, different user's reply to the answer above:


It's in the third screenshot above (just above this), that I found something that will stick with me on Python exception handling: be as precise as is feasible in order to catch only the exceptions that matter for the program/module in question.

And here's some code that I wrote (and partially reused from Randal's video #5 from module07), to show how to get past a built-in ValueError exception in Python that fires when user input is used to create an integer object but the user enters a string that cannot be converted to an integer.

while True:
    try:
        v2 = int(input('Enter a number: '))
    except ValueError:
        v2 = int(input('Enter only an integer: '))
    .
    .
    .
    break


I had also seen pickling before, but definitely needed a refresher. In this module, Randal mentioned that one advantage of pickling data from text to binary was the ability to make key data somewhat less accessible to users.

I found this useful post from ThoughtCo. (after searching "Python 3 why pickle data" on DDG). Specifically, I liked this:


So, pickling is used to enable data "persistence". I thought about how we have been reading from and writing to a text file to maintain our "To-Do" list. Then I thought, "can pickling be used to take the text file out of the equation (so to speak)?"

I refactored code from Assignment06 to use pickle methods to load and dump data to a binary file called "ToDo.dat".

obj_file = open('ToDo.dat', 'rb')
bin_data = obj_file.read()
graph_data = pickle.loads(bin_data, encoding='utf-8')  # Note that load() only loads one row of data.

Now, I know that using the read method here reads all of the data in ToDo.dat. And I know that bin_data is a bytes object, so pickle.loads( ) should deserialize all of bin_data. But I wasn't able to retrieve all of the data from ToDo.dat.

I was successful using the pickle.dump( ) method to save data to ToDo.dat, however.

obj_file = open('ToDo.dat', 'wb')
for dic in lst_table:
    str_dic = str(dic)
    str_dic = str_dic.replace('{', '')
    str_dic = str_dic.replace('}', '')
    str_dic = str_dic.replace('\'', '')
    str_dic = str_dic.replace(':', ',')
    str_dic = str_dic.replace(', ', ',')
    pickle.dump(str_dic, obj_file)
obj_file.close()


Thus concludes (for now, anyway) my work on this assignment.

Comments