Record in Python

In Python, a record can be effectively represented using a class instance. This approach allows for the dynamic creation and access of fields using dot notation, providing a flexible way to store and manage data. This method is particularly useful when you need a simple structure to hold data without the overhead of more complex data structures.

Using a Class Instance as a Record

A class in Python can be used to create a simple record structure. By defining a class and then creating an instance of it, you can dynamically add attributes to the instance to store data. Here's an example of how you can use a class instance to represent a record:

class Circle:
    pass

my_circle = Circle()
my_circle.radius = 5
print(2 * 3.14 * my_circle.radius)

# [Output: 31.4](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-15/16)

In this example, a class Circle is defined without any predefined attributes. An instance my_circle is created, and a radius attribute is dynamically added to it. This attribute can then be accessed using dot notation to perform calculations, such as computing the circumference of the circle.

Reading and Unpacking Binary Records

When dealing with binary data, Python provides the struct module, which allows you to read and unpack records from a binary file. The struct.unpack function is used to convert a binary record into a tuple of Python values based on a specified format string. This is particularly useful for reading structured binary data.

Here's an example of how to read and unpack records from a binary file:

import struct

record_format = 'hd7s'
record_size = struct.calcsize(record_format)
result_list = []
with open("data", 'rb') as input: 
    while True:
        record = input.read(record_size)  #A         
        if not record:  #B
            break
        result_list.append(struct.unpack(record_format, record))  #C

print(result_list)

# [Output: [(42, 3.14, b'goodbye')]](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-15/16)
#A Reads in a single record
#B Checks to see if record is not empty
#C Unpacks record into a tuple; appends to results

In this code snippet, the struct.unpack function is used to read records from a binary file named "data". The format string 'hd7s' specifies the data types and sizes of the fields in the record. The record_size is calculated using struct.calcsize, and the file is read in chunks of this size. Each record is unpacked into a tuple and appended to result_list. If an empty record is encountered, it indicates the end of the file, and the loop is terminated.