Skip to main content

A Python utility for making child classes savable,

Project description

Savable

Savable is a Python utility for making child classes savable, providing methods to save and load objects using various formats such as pickle, zip, dict, and json. It also offers a mechanism to exclude certain attributes from being saved, useful for non-serializable class attributes or those not needed to be saved.

Installation

The package can be installed via pip:

pip install savable

Usage

Basic Usage

from savable import Savable

class MyClass(Savable):
    def __init__(self, name):
        self.name = name
        self.surname = 'none'
        

obj = MyClass("example")
obj.surname = 'example_surname' # change instance attribute after initialization
obj.save("example.pkl")  # Save object to pickle file
obj.to_dict()  # Output: {"name": "example","surname":"example_surname"}
obj.to_json("example.json")  # Save object to JSON file
obj.to_zip("example.zip")  # Save object to zip file

Usage with dataclasses

from savable import Savable
from dataclasses import dataclass

@dataclass
class MyActor(Savable):
    name:str 
    surname:str
    kind:str = 'human'    

 
obj = MyActor(name='jack',surname='black') 
obj.to_dict()  # Output: {"name": "jack","surname":"black","kind":"human"}
MyActor.from_dict(obj.to_dict()) # Output: MyActor(name='jack', surname='black', kind='human')

Loading from File

The class will inference the file format from the extension. Supported extensions are:

  1. from_pickle (.pkl,.pickle)
  2. from_zip (.zip)
  3. from_json (.json, .cfg)
loaded_obj = MyClass.load("example.pkl")  # Load object from pickle file
print(loaded_obj.name)  # Output: example

Dealing with Dictionary serialization

To save and load an object from a dictionary, you can use the to_dict and from_dict methods.

When creating an instance from a given dictionary, the class will try to bind the dictionary keys to the class init signature. If all the mandatory arguments are present, (i.e. the class is easy-serializable) the class will first call the init method, and then it will overwrite the attributes with corresponding dictionary values.

If the dictionary is missing some mandatory arguments, by default the class will raise a NotSimplySerializable exception.

However, specifying the force parameter to True, a new instance will be created, without calling the init method.

This is useful when the class is not easy-serializable or when you want to forse instance creation from a dictionary exported from an old version of the class.

class MyClass(Savable):
    def __init__(self, name,mandatory_arg):
        self.name = str(name) + str(mandatory_arg) 
        # mandatoy_arg is not saved as attribute so the class is not easy-serializable
        

obj = MyClass("example","_mandatory_arg")
obj_dict = obj.to_dict()
print(obj_dict)  # Output: {"name": "example_mandatory_arg"}
new_obj = MyClass.from_dict(obj_dict) # raise NotSimplySerializable exception
new_obj = MyClass.from_dict(obj_dict,force=True) # create a new instance without calling __init__ method

Excluding Attributes from Saving

You can specify attributes to exclude from saving by providing a list to exclude_from_saving parameter in the class constructor:

class MyClass(Savable):
    def __init__(self, name, logger):
        self.name = name
        self.logger = logger
        super().__init__(exclude_from_saving=["logger"])

obj = MyClass("example", logger)
obj.save("example.pkl")

Supported Formats

The Savable class supports saving and loading objects in the following formats:

  • Pickle (.pkl): Binary serialization format.
  • Zip (.zip): Compressed archive containing pickle file.
  • JSON (.json): JSON serialization format.

Documentation

For more detailed documentation, including additional options and methods, please refer to the API Documentation.

Contributing

Contributions are welcome! Please feel free to open an issue or submit a pull request with any improvements.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

savable-1.0.0.tar.gz (8.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

savable-1.0.0-py3-none-any.whl (7.5 kB view details)

Uploaded Python 3

File details

Details for the file savable-1.0.0.tar.gz.

File metadata

  • Download URL: savable-1.0.0.tar.gz
  • Upload date:
  • Size: 8.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.9.19

File hashes

Hashes for savable-1.0.0.tar.gz
Algorithm Hash digest
SHA256 0865a58e51302f6df6f2b432fd368bd63e6e6d13204c741fc261f1d7000d7bcb
MD5 f127febac12a904adee8b503bd65bd76
BLAKE2b-256 1bafe7c8337182fc97a73539b2a73005d3a772aaac03c77053510d125d8866ba

See more details on using hashes here.

File details

Details for the file savable-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: savable-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 7.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.9.19

File hashes

Hashes for savable-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e1c80de050bfb3e8c6ad2ec486ed4ae1f95b0e2e950d1809d90b6fe9c4f7e096
MD5 9e49de70a3a16e469138847cef85c791
BLAKE2b-256 49bb6bfa309f9e6b9eb93f4e5ad804470b3eb061ebaa27bc6f10377bedb04e8b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page