[Tutor] associating two objects without ORM and processing a text file

Steven D'Aprano steve at pearwood.info
Tue Feb 12 01:58:31 CET 2013

On 11/02/13 16:14, neubyr wrote:
> I have a text file with each line in following format:
> Book Name, Author Name, Genre, Publication Date
> I would like to perform following queries on this file:
>   * Get all books written by an author
>   * Remove all books of an author
>   * Get information about a book (pretty print matching line!)
>   * Get books of particular genre
> Also, I would like to add and delete entries in this file. I am not
> planning to use any database for this purpose and would like to get better
> grasp on file parsing and classes/OOP. I need some help in creating classes
> and following are my initial thoughts:
> # Create a class for Book object
> class Book:
>    atributes: name, author_name, genre, publication-date

You could use a class. But since Books don't have any behaviour, a simple
struct or record would be better than a class:

from collections import namedtuple
Book = namedtuple("Book", "name author genre date")

lotr = Book("The Hobbit", "J.R.R. Tolkien", "Fantasy", "1937")

This has the advantage of simplicity. But if you need to add behaviour to the
Book class, e.g. validation of the fields, you should be able to inherit from
a named tuple. Untested:

class Book(namedtuple("Book", "name author genre date")):
     def genre(self):
         return super(Book, self).genre
     @genre.setter(self, value):
         super(Book, self).genre = value.title()  # 'fantasy' -> 'Fantasy'

> # Create
> Author:
>   attribute(s): name

As Alan suggested, a waste of time. Since the Author has no behaviour and
only a single field, why not just use a string?

> # Create class for reading and writing to the file
> class Booksfile:
>    methods: ??

Why should this be a class? This is not Java.


Just write a function that reads a file and returns a list of Books.

Or perhaps I should say:

     return_type=list, return_item_values=Book)

> * How do I associate/relate Book and Author classes so that it will help me
> in getting information like 'get list of books written by an author'? Data
> attribute?

You want to map authors to books. Whenever you want a mapping, use a dict:

data = {
     'J.R.R. Tolkien': [Book("The Hobbit"), Book("The Lord of the Rings")],
     'Tom Clancy': [Book("The Hunt for Red October")],
     'Terry Pratchett': [Book('Small Gods'), Book('Night Watch'),
     'Stephenie Meyer': [
         Book('Something about abusive boyfriends but that's okay because they sparkle')],

> * Should I create a new Booksfile object for reading, writing and deleting
> entries in the file OR add corresponding methods to the book object itself?

Heavens no. Why should the book know about the library catalog it is listed in?
Your book class should be responsible for the book, and nothing but the book.


More information about the Tutor mailing list