Python Advanced: Custom Context Managers


In Python, context managers allow for the allocation and release of resources precisely when you want. This tutorial introduces a custom context manager for handling JSON files efficiently.

Code Example

from json import load
class Json:
    #executed before init, creates the object manually
    def __new__(cls, file):
        print("object called")
        inst = object.__new__(cls)
        return inst

    #class variable
    how_many_times_used = 0

    def __init__(self, filename):
        self.__fn = open(filename, "rt")
        self.__data = load(self.__fn)
        Json.how_many_times_used += 1
    
    def __enter__(self):
        return self.__data
    
    def __exit__(self, tipe, value, traceback):
        self.__fn.close()

with Json("students.json") as data:
    print(data)
    print(data[0]['name'])

print(Json.how_many_times_used)

Example students.json
[
    {
        "name": "John Doe",
        "age": 22,
        "course": "Computer Science"
    },
    {
        "name": "Jane Smith",
        "age": 20,
        "course": "Physics"
    }
]
Output will appear here when the button is clicked.

How It Works

This custom context manager class for JSON handling automates opening and closing files. It leverages Python's magic methods __enter__ and __exit__ to manage resources, ensuring that the file is properly closed after operations, thus avoiding file corruption or data loss.

Conclusion

Implementing a custom context manager like this not only makes your code cleaner but also safer and more efficient by handling resources automatically.

Enquiries

[email protected]

Copyright © 2023 - slash-root.com