Outils pour utilisateurs

Outils du site


issue172:python

Ceci est une ancienne révision du document !


Well, I’ve made it. 10 full years worth of Python articles in the series. Actually, it’s been over 10 years in calendar time, but as far as articles are concerned, it’s 10 years worth. Thank you, dear readers, for hanging in with me for so long.

Way back in the dawn of time, when rainbows were in black-and-white, and we had to watch television by candlelight because electricity hadn’t been invented yet, one of the first programming languages I learned well was Pascal. Along with everything else that Pascal had to offer, there was a data structure named Records. Records were special User Defined data types that would allow the programmer to set up a logical grouping of data using existing primitive types line string, integers, reals, and so on. When we would define a record, it would look something like this (top right).

And so on. We could use an array of the records to maintain a very simple database type structure.

Run the clock forward, and I eventually added Visual Basic (both DOS and Windows versions) to my toolkit of programming languages. Visual Basic also had a similar user defined type, but it was called a structure. You would define the structure like this:

Public Structure TbookRec

  Public Title as String
  Public Author as String
  Public ISBN as String
  Public Price as Decimal

End Structure

Dim myBookRec as TbookRec TbookRec.Title = “I Robot” TbookRec.Author = “Isaac Asimov”

And on and on. When I came to Python (it was back before 3.0 came out), there wasn’t a convenient data structure like these. Having done a tonne of database work in my previous projects, I was somewhat at a loss. How could such a cool programming language like Python not have a structure like other languages.

This month, we will be looking at dataclasses, something that was introduced back in Python 3.7: • Namedtuples were introduced back in Python 2.6 but namedtuples, like any tuples, are immutable. • Dataclasses are easy to use, easy to read, and are mutable.

We’ll create a very simple (and unrealistic) small book store point of sale demo. Here’s how to start working with dataclasses.

First, you have to import them into your project. They are a part of the dataclasses library.

from dataclasses import dataclass

Next, you need to add a decorator to start defining your class. The dataclass is like almost any other classes, but the init and repr functions, as well as a few other basic functions, are automatically created for you. We’ll take the structure from the discussion above…

@dataclass class TbookRec:

  Title : str
  Author : str
  ISBN : str
  Price : float
  QtyOnHand : int

Notice I added a field, QtyOnHand in our example. This makes it a bit more realistic but still minimal and a good way to demo the dataclass. At this point, we need to define an empty list to hold the record structures, and then create our in memory “database” by creating various “books” that will be in our imaginary store inventory.

myRecs = []

To make things a bit cleaner, we’ll create a function to do all the “database” entries at one time. We load the data into the dataclass and then append it to the myRecs list and “rinse and repeat”. I’ll show the creation of only three records, but in the demo file from the repository, I create five records. The main thing I want to show here is that inserting data into a dataclass is simple. So simple in fact, that, assuming you maintain the order of variables, you don’t have to include the field names. If you don’t keep the order of the variables, you must include the field names (top right).

So you should see that it’s not only easy to put data into the dataclass record structure, but also to get the data that you want out just as easily.

Now let’s create a function to search the recordset by author. Again, this is not a realistic search function, just a very simple one. The author name must be entered the way it is when it was put into the dataclass instances (bottom right).

The output of the search function for Author looks like this…

Title: The Hitchiker's Guide to the Galaxy Author: Douglas Adams ISBN: 978-0345391803 Price: 6.83 Qty: 1

Title: The Restaurant at the End of the Universe Author: Douglas Adams ISBN: 978-1529034530 Price: 7.99 Qty: 0

Now another simple function to search by book title. Remember, I’m not trying to cover any typos, capitalization errors, etc. Just trying to make it simple to show the ease of dealing with searching the data (top right).

And it’s output is like this…

Enter Book Title → I Robot Title: I Robot Author: Isaac Asimov ISBN: 978-0553382563 Price: 6.79 Qty: 2 … Enter Book Title → Raise The Titanic Title: Raise The Titanic Author: Clive Cussler ISBN: 978-0425194522 Price: 9.99 Qty: 1

We’ll create one more very simple search function, this time by ISBN (bottom right).

The output is as follows:

Enter ISBN → 978-1529034530 Title: The Restaurant at the End of the Universe Author: Douglas Adams ISBN: 978-1529034530 Price: 7.99 Qty: 0

Now that we’ve covered the simple search functions, it only makes sense to add a function to “sell” one of our books. This also shows how easy it is to modify one of the dataclass items. We’ll “sell” one of our two copies of “I Robot”.

While not grammatically correct, here is the output. (As my sainted mother would say, “Do as I say do, not as I do do.”)

Enter Title →I Robot There are now 1 book(s) left in stock.

And just to make sure, you can call for a refresh of the book data, the list of books shows that we did in fact decrement the quantity-on-hand for that book by calling the book function.

Number of Unique Books: 5 Title: I Robot Author: Isaac Asimov Price: 6.79 Qty: 1 Title: The Gentle Giants of Ganymede Author: James P. Hogan Price: 6.11 Qty: 1 Title: Raise The Titanic Author: Clive Cussler Price: 9.99 Qty: 1 Title: The Hitchiker's Guide to the Galaxy Author: Douglas Adams Price: 6.83 Qty: 1 Title: The Restaurant at the End of the Universe Author: Douglas Adams Price: 7.99 Qty: 0

Now, last but not least, let’s create a “work” loop that offers a simple menu to handle the calls to the various functions (top right).

So, I hope you find the use of dataclasses helpful in your future projects.

If you want to learn more about Python dataclasses, you would do well to check out the really good discussion and guide at Real Python (https://realpython.com/python-data-classes/) written by Geir Arne Hjelle.

You’ll be able to find the code for this month’s article at my github repository at https://github.com/gregwa1953/FCM-172 .

Until next time, as always; stay safe, healthy, positive and creative!

issue172/python.1630309170.txt.gz · Dernière modification : 2021/08/30 09:39 de auntiee