Name | savable JSON |
Version |
1.0.0
JSON |
| download |
home_page | None |
Summary | A Python utility for making child classes savable, |
upload_time | 2024-04-17 07:13:10 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.9 |
license | MIT License Copyright (c) 2024 gtanzi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
keywords |
savable
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
# 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:
```bash
pip install savable
```
## Usage
### Basic Usage
```python
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
```python
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)
```python
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.
```python
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:
```python
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](https://github.com/your-username/savable).
## 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](LICENSE) file for details.
Raw data
{
"_id": null,
"home_page": null,
"name": "savable",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.9",
"maintainer_email": null,
"keywords": "savable",
"author": null,
"author_email": "Giacomo Tanzi <giacomo.tanzi14@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/1b/af/e7c8337182fc97a73539b2a73005d3a772aaac03c77053510d125d8866ba/savable-1.0.0.tar.gz",
"platform": null,
"description": "\r\n# Savable\r\n\r\n**Savable** is a Python utility for making child classes savable, \r\nproviding methods to save and load objects using various formats \r\nsuch as pickle, zip, dict, and json. \r\nIt also offers a mechanism to exclude certain attributes from being saved, \r\nuseful for non-serializable class attributes or those not needed to be saved.\r\n\r\n## Installation\r\n\r\nThe package can be installed via pip:\r\n\r\n```bash\r\npip install savable\r\n```\r\n\r\n## Usage\r\n\r\n### Basic Usage\r\n\r\n```python\r\nfrom savable import Savable\r\n\r\nclass MyClass(Savable):\r\n def __init__(self, name):\r\n self.name = name\r\n self.surname = 'none'\r\n \r\n\r\nobj = MyClass(\"example\")\r\nobj.surname = 'example_surname' # change instance attribute after initialization\r\nobj.save(\"example.pkl\") # Save object to pickle file\r\nobj.to_dict() # Output: {\"name\": \"example\",\"surname\":\"example_surname\"}\r\nobj.to_json(\"example.json\") # Save object to JSON file\r\nobj.to_zip(\"example.zip\") # Save object to zip file\r\n```\r\n\r\n### Usage with dataclasses\r\n\r\n```python\r\nfrom savable import Savable\r\nfrom dataclasses import dataclass\r\n\r\n@dataclass\r\nclass MyActor(Savable):\r\n name:str \r\n surname:str\r\n kind:str = 'human' \r\n\r\n \r\nobj = MyActor(name='jack',surname='black') \r\nobj.to_dict() # Output: {\"name\": \"jack\",\"surname\":\"black\",\"kind\":\"human\"}\r\nMyActor.from_dict(obj.to_dict()) # Output: MyActor(name='jack', surname='black', kind='human')\r\n```\r\n\r\n### Loading from File\r\nThe class will inference the file format from the extension.\r\nSupported extensions are: \r\n1) from_pickle (.pkl,.pickle) \r\n2) from_zip (.zip)\r\n3) from_json (.json, .cfg)\r\n\r\n\r\n```python\r\nloaded_obj = MyClass.load(\"example.pkl\") # Load object from pickle file\r\nprint(loaded_obj.name) # Output: example\r\n```\r\n\r\n### Dealing with Dictionary serialization\r\nTo save and load an object from a dictionary, you can use the `to_dict` and `from_dict` methods.\r\n\r\nWhen creating an instance from a given dictionary, the class will try to bind the dictionary \r\nkeys to the class __init__ signature. \r\nIf all the mandatory arguments are present, (i.e. the class is *easy-serializable*) \r\nthe class will **first call \r\nthe __init__ method**, and **then it will overwrite the attributes** with corresponding dictionary values.\r\n\r\n\r\nIf the dictionary is\r\nmissing some mandatory arguments, by default the class will raise a *NotSimplySerializable* exception.\r\n\r\nHowever, specifying the `force` parameter to True, a new instance will be created, \r\n**without calling the __init__ method**.\r\n\r\nThis is useful when the class is not *easy-serializable* or \r\nwhen you want to forse instance creation from a dictionary exported from an old version of the class.\r\n\r\n```python\r\nclass MyClass(Savable):\r\n def __init__(self, name,mandatory_arg):\r\n self.name = str(name) + str(mandatory_arg) \r\n # mandatoy_arg is not saved as attribute so the class is not easy-serializable\r\n \r\n\r\nobj = MyClass(\"example\",\"_mandatory_arg\")\r\nobj_dict = obj.to_dict()\r\nprint(obj_dict) # Output: {\"name\": \"example_mandatory_arg\"}\r\nnew_obj = MyClass.from_dict(obj_dict) # raise NotSimplySerializable exception\r\nnew_obj = MyClass.from_dict(obj_dict,force=True) # create a new instance without calling __init__ method\r\n\r\n```\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n### Excluding Attributes from Saving\r\n\r\nYou can specify attributes to exclude from saving by providing a list to `exclude_from_saving` parameter in the class constructor:\r\n\r\n```python\r\nclass MyClass(Savable):\r\n def __init__(self, name, logger):\r\n self.name = name\r\n self.logger = logger\r\n super().__init__(exclude_from_saving=[\"logger\"])\r\n\r\nobj = MyClass(\"example\", logger)\r\nobj.save(\"example.pkl\")\r\n```\r\n\r\n\r\n### Supported Formats\r\n\r\nThe `Savable` class supports saving and loading objects in the following formats:\r\n\r\n- **Pickle (.pkl)**: Binary serialization format.\r\n- **Zip (.zip)**: Compressed archive containing pickle file.\r\n- **JSON (.json)**: JSON serialization format.\r\n\r\n## Documentation\r\n\r\nFor more detailed documentation, including additional options and methods, please refer to the [API Documentation](https://github.com/your-username/savable).\r\n\r\n## Contributing\r\n\r\nContributions are welcome! Please feel free to open an issue or submit a pull request with any improvements.\r\n\r\n## License\r\n\r\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\r\n\r\n",
"bugtrack_url": null,
"license": "MIT License Copyright (c) 2024 gtanzi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ",
"summary": "A Python utility for making child classes savable,",
"version": "1.0.0",
"project_urls": {
"Homepage": "https://github.com/gtanzi/savable"
},
"split_keywords": [
"savable"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "49bb6bfa309f9e6b9eb93f4e5ad804470b3eb061ebaa27bc6f10377bedb04e8b",
"md5": "9e49de70a3a16e469138847cef85c791",
"sha256": "e1c80de050bfb3e8c6ad2ec486ed4ae1f95b0e2e950d1809d90b6fe9c4f7e096"
},
"downloads": -1,
"filename": "savable-1.0.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "9e49de70a3a16e469138847cef85c791",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.9",
"size": 7497,
"upload_time": "2024-04-17T07:13:08",
"upload_time_iso_8601": "2024-04-17T07:13:08.815701Z",
"url": "https://files.pythonhosted.org/packages/49/bb/6bfa309f9e6b9eb93f4e5ad804470b3eb061ebaa27bc6f10377bedb04e8b/savable-1.0.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "1bafe7c8337182fc97a73539b2a73005d3a772aaac03c77053510d125d8866ba",
"md5": "f127febac12a904adee8b503bd65bd76",
"sha256": "0865a58e51302f6df6f2b432fd368bd63e6e6d13204c741fc261f1d7000d7bcb"
},
"downloads": -1,
"filename": "savable-1.0.0.tar.gz",
"has_sig": false,
"md5_digest": "f127febac12a904adee8b503bd65bd76",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9",
"size": 8235,
"upload_time": "2024-04-17T07:13:10",
"upload_time_iso_8601": "2024-04-17T07:13:10.976275Z",
"url": "https://files.pythonhosted.org/packages/1b/af/e7c8337182fc97a73539b2a73005d3a772aaac03c77053510d125d8866ba/savable-1.0.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-04-17 07:13:10",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "gtanzi",
"github_project": "savable",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"requirements": [],
"lcname": "savable"
}