parameterizable


Nameparameterizable JSON
Version 0.103.8 PyPI version JSON
download
home_pageNone
SummaryLibrary for work with parameterizable classes.
upload_time2025-10-29 04:14:12
maintainerNone
docs_urlNone
authorVlad (Volodymyr) Pavlov
requires_python>=3.10
licenseMIT
keywords parameters
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # parameterizable
[![PyPI version](https://img.shields.io/pypi/v/parameterizable.svg)](https://pypi.org/project/parameterizable/)
[![Python versions](https://img.shields.io/pypi/pyversions/parameterizable.svg)](https://pypi.org/project/parameterizable/)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Downloads](https://img.shields.io/pypi/dm/parameterizable?color=blue)](https://pypistats.org/packages/parameterizable)
[![Documentation Status](https://app.readthedocs.org/projects/parameterizable/badge/?version=latest)](https://parameterizable.readthedocs.io/en/latest/)
[![Code style: pep8](https://img.shields.io/badge/code_style-pep8-blue.svg)](https://peps.python.org/pep-0008/)
[![Docstring Style: Google](https://img.shields.io/badge/docstrings_style-Google-blue)](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html)

Parameter manipulation for Python classes.

## What Is It?

`parameterizable` provides functionality for work with parameterizable 
classes: those that have (hyper) parameters which define object's configuration,
that is different from the object's internal contents or data. Such parameters 
are typically passed to the `.__init__()` method when an object is created.

`parameterizable` allows to:
* Get parameters of an object as a dictionary.
* Get default parameters of a class as a dictionary.
* Serialize an object's parameters to a JSON string. 
* Recreate the object from its parameters, stored in a JSON string.

## Why Is It Useful?

`parameterizable` is useful for developers working with 
configurable Python objects, especially in scenarios involving 
machine learning, scientific computing, or any domain where 
object's behavior is defined by the object's parameters. It provides:

* **Consistency**: Ensures a standardized way to handle parameters 
across different classes.
* **Serialization**: Simplifies saving and loading configuration-defined objects
using JSON.
* **Reproducibility**: Facilitates recreating objects with the same configuration, 
which is critical for debugging and sharing experiments.

By abstracting parameter handling, this library reduces boilerplate code 
and improves maintainability.

## Usage

Most users will:
- Inherit from `ParameterizableClass` in their own classes, 
- Implement the `.get_params()` method to expose the configuration needed to recreate the object, and (sometimes)
- Implement the `.essential_param_names` property to expose the core parameters which determine the object's behavior.


## Key Classes, Methods and Functions,

- `ParameterizableClass`: Base class for parameterizable objects. Derive your class from it to enable the library’s features.
- `NotPicklableClass`: Mixin that prevents pickling/unpickling; inherit from it to make your class explicitly non-picklable.
- `JsonSerializedObject`: A string containing JSON-serialized object.
- `ParameterizableClass.get_params()`: Implement in your subclass to return the configuration dictionary 
needed to recreate the object.
- `ParameterizableClass.get_default_params()`: Class method returning default parameters for the class as a dictionary.
- `ParameterizableClass.essential_param_names`: Implement in your subclass to return the names of the core parameters
which determine the object's behavior. If not implemented, all parameters are considered essential.
- `ParameterizableClass.auxiliary_param_names`: A property that returns the names of the auxiliary parameters.
- `ParameterizableClass.get_jsparams()`: A method that serializes an object's parameters 
to a JSON string (`JsonSerializedObject`).
- `ParameterizableClass.get_essential_jsparams()`: A method that returns a JSON string with essential parameters only.
- `ParameterizableClass.get_auxiliary_jsparams()`: A method that returns a JSON string with auxiliary parameters only.
- `ParameterizableClass.get_default_jsparams()`: Class method returning default parameters for the class as a JSON string.
- `dumpjs(obj)`: Return a JSON string representation of an object.
- `loadjs(js)`: Return an object from a JSON string.
- `update_jsparams(js, updates)`: Return a new JSON string with selected parameters updated without full deserialization.
- `access_jsparams(js, names)`: Return a dict with a subset of params, stored inside a JSON string.
- `sort_dict_by_keys(d)`: Utility to produce a new dict whose keys are sorted alphabetically.

## How To Get It?

The source code is hosted on GitHub at:
[https://github.com/pythagoras-dev/parameterizable](https://github.com/pythagoras-dev/parameterizable) 

Binary installers for the latest released version are available at the Python package index at:
[https://pypi.org/project/parameterizable](https://pypi.org/project/parameterizable)

Using uv :
```
uv add parameterizable
```

Using pip (legacy alternative to uv):
```
pip install parameterizable
```

## Requirements

- Python >= 3.10
- Runtime dependencies: none

For development:
- pytest (optional)

## Quick Start

Here's a minimal example showing how to make your class parameterizable and serialize/deserialize it:

```python
from parameterizable.parameterizable import ParameterizableClass
from parameterizable.json_processor import dumpjs, loadjs

class MyModel(ParameterizableClass):
    def __init__(self, n_trees=10, depth=3, verbose=False):
        self.n_trees = n_trees
        self.depth = depth
        self.verbose = verbose

    def get_params(self) -> dict:
        # Only values returned here are considered this object's "parameters"
        return {"n_trees": self.n_trees, "depth": self.depth, "verbose": self.verbose}

    # Optional: list the parameters that define identity/behavior
    @property
    def essential_param_names(self) -> set[str]:
        return {"n_trees", "depth"}

m = MyModel(n_trees=50, depth=5, verbose=True)

# Serialize parameters to JSON
js = dumpjs(m)

# Recreate an equivalent object from JSON
m2 = loadjs(js)
assert isinstance(m2, MyModel)
assert m2.get_params() == m.get_params()
```

## API Examples

- Update parameters in JSON without full deserialization:

```python
from parameterizable.json_processor import update_jsparams, dumpjs, loadjs

js2 = update_jsparams(js, n_trees=100)  # returns a new JSON string
m3 = loadjs(js2)
assert m3.n_trees == 100
```

- Access a subset of parameters directly from JSON:

```python
from parameterizable.json_processor import access_jsparams

subset = access_jsparams(js2, "n_trees", "depth")
assert subset == {"n_trees": 100, "depth": 5}
```

- Work with essential/auxiliary parameters:

```python
m.get_essential_params()      # {"n_trees": 50, "depth": 5}
m.get_essential_jsparams()    # JSON string with only essential params
m.get_auxiliary_params()      # {"verbose": True}
m.get_auxiliary_jsparams()    # JSON string with only auxiliary params
```

- Sort dictionaries by keys (utility):

```python
from parameterizable.dict_sorter import sort_dict_by_keys
sort_dict_by_keys({"b": 2, "a": 1})  # {"a": 1, "b": 2}
```

- Prevent pickling/unpickling using NotPicklableClass:

```python
import pickle
from parameterizable import NotPicklableClass

class Connection(NotPicklableClass):
    pass

conn = Connection()

# Any attempt to pickle or unpickle will raise TypeError
try:
    pickle.dumps(conn)
except TypeError:
    print("Connection cannot be pickled")
```

## Development

- Run tests:
  - With pytest: `pytest`
  - Or via Python: `python -m pytest`
- Supported Python versions: 3.10+
- See contributing guidelines: [contributing.md](contributing.md)

## License

This project is licensed under the MIT License — see [LICENSE](LICENSE) for details.

## Key Contacts

* [Vlad (Volodymyr) Pavlov](https://www.linkedin.com/in/vlpavlov/)

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "parameterizable",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": "parameters",
    "author": "Vlad (Volodymyr) Pavlov",
    "author_email": "Vlad (Volodymyr) Pavlov <vlpavlov@ieee.org>",
    "download_url": "https://files.pythonhosted.org/packages/45/24/bcc719f41cac5012ade18878b8d80886380df798837eaa32bb1d7ea098aa/parameterizable-0.103.8.tar.gz",
    "platform": null,
    "description": "# parameterizable\n[![PyPI version](https://img.shields.io/pypi/v/parameterizable.svg)](https://pypi.org/project/parameterizable/)\n[![Python versions](https://img.shields.io/pypi/pyversions/parameterizable.svg)](https://pypi.org/project/parameterizable/)\n[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)\n[![Downloads](https://img.shields.io/pypi/dm/parameterizable?color=blue)](https://pypistats.org/packages/parameterizable)\n[![Documentation Status](https://app.readthedocs.org/projects/parameterizable/badge/?version=latest)](https://parameterizable.readthedocs.io/en/latest/)\n[![Code style: pep8](https://img.shields.io/badge/code_style-pep8-blue.svg)](https://peps.python.org/pep-0008/)\n[![Docstring Style: Google](https://img.shields.io/badge/docstrings_style-Google-blue)](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html)\n\nParameter manipulation for Python classes.\n\n## What Is It?\n\n`parameterizable` provides functionality for work with parameterizable \nclasses: those that have (hyper) parameters which define object's configuration,\nthat is different from the object's internal contents or data. Such parameters \nare typically passed to the `.__init__()` method when an object is created.\n\n`parameterizable` allows to:\n* Get parameters of an object as a dictionary.\n* Get default parameters of a class as a dictionary.\n* Serialize an object's parameters to a JSON string. \n* Recreate the object from its parameters, stored in a JSON string.\n\n## Why Is It Useful?\n\n`parameterizable` is useful for developers working with \nconfigurable Python objects, especially in scenarios involving \nmachine learning, scientific computing, or any domain where \nobject's behavior is defined by the object's parameters. It provides:\n\n* **Consistency**: Ensures a standardized way to handle parameters \nacross different classes.\n* **Serialization**: Simplifies saving and loading configuration-defined objects\nusing JSON.\n* **Reproducibility**: Facilitates recreating objects with the same configuration, \nwhich is critical for debugging and sharing experiments.\n\nBy abstracting parameter handling, this library reduces boilerplate code \nand improves maintainability.\n\n## Usage\n\nMost users will:\n- Inherit from `ParameterizableClass` in their own classes, \n- Implement the `.get_params()` method to expose the configuration needed to recreate the object, and (sometimes)\n- Implement the `.essential_param_names` property to expose the core parameters which determine the object's behavior.\n\n\n## Key Classes, Methods and Functions,\n\n- `ParameterizableClass`: Base class for parameterizable objects. Derive your class from it to enable the library\u2019s features.\n- `NotPicklableClass`: Mixin that prevents pickling/unpickling; inherit from it to make your class explicitly non-picklable.\n- `JsonSerializedObject`: A string containing JSON-serialized object.\n- `ParameterizableClass.get_params()`: Implement in your subclass to return the configuration dictionary \nneeded to recreate the object.\n- `ParameterizableClass.get_default_params()`: Class method returning default parameters for the class as a dictionary.\n- `ParameterizableClass.essential_param_names`: Implement in your subclass to return the names of the core parameters\nwhich determine the object's behavior. If not implemented, all parameters are considered essential.\n- `ParameterizableClass.auxiliary_param_names`: A property that returns the names of the auxiliary parameters.\n- `ParameterizableClass.get_jsparams()`: A method that serializes an object's parameters \nto a JSON string (`JsonSerializedObject`).\n- `ParameterizableClass.get_essential_jsparams()`: A method that returns a JSON string with essential parameters only.\n- `ParameterizableClass.get_auxiliary_jsparams()`: A method that returns a JSON string with auxiliary parameters only.\n- `ParameterizableClass.get_default_jsparams()`: Class method returning default parameters for the class as a JSON string.\n- `dumpjs(obj)`: Return a JSON string representation of an object.\n- `loadjs(js)`: Return an object from a JSON string.\n- `update_jsparams(js, updates)`: Return a new JSON string with selected parameters updated without full deserialization.\n- `access_jsparams(js, names)`: Return a dict with a subset of params, stored inside a JSON string.\n- `sort_dict_by_keys(d)`: Utility to produce a new dict whose keys are sorted alphabetically.\n\n## How To Get It?\n\nThe source code is hosted on GitHub at:\n[https://github.com/pythagoras-dev/parameterizable](https://github.com/pythagoras-dev/parameterizable) \n\nBinary installers for the latest released version are available at the Python package index at:\n[https://pypi.org/project/parameterizable](https://pypi.org/project/parameterizable)\n\nUsing uv :\n```\nuv add parameterizable\n```\n\nUsing pip (legacy alternative to uv):\n```\npip install parameterizable\n```\n\n## Requirements\n\n- Python >= 3.10\n- Runtime dependencies: none\n\nFor development:\n- pytest (optional)\n\n## Quick Start\n\nHere's a minimal example showing how to make your class parameterizable and serialize/deserialize it:\n\n```python\nfrom parameterizable.parameterizable import ParameterizableClass\nfrom parameterizable.json_processor import dumpjs, loadjs\n\nclass MyModel(ParameterizableClass):\n    def __init__(self, n_trees=10, depth=3, verbose=False):\n        self.n_trees = n_trees\n        self.depth = depth\n        self.verbose = verbose\n\n    def get_params(self) -> dict:\n        # Only values returned here are considered this object's \"parameters\"\n        return {\"n_trees\": self.n_trees, \"depth\": self.depth, \"verbose\": self.verbose}\n\n    # Optional: list the parameters that define identity/behavior\n    @property\n    def essential_param_names(self) -> set[str]:\n        return {\"n_trees\", \"depth\"}\n\nm = MyModel(n_trees=50, depth=5, verbose=True)\n\n# Serialize parameters to JSON\njs = dumpjs(m)\n\n# Recreate an equivalent object from JSON\nm2 = loadjs(js)\nassert isinstance(m2, MyModel)\nassert m2.get_params() == m.get_params()\n```\n\n## API Examples\n\n- Update parameters in JSON without full deserialization:\n\n```python\nfrom parameterizable.json_processor import update_jsparams, dumpjs, loadjs\n\njs2 = update_jsparams(js, n_trees=100)  # returns a new JSON string\nm3 = loadjs(js2)\nassert m3.n_trees == 100\n```\n\n- Access a subset of parameters directly from JSON:\n\n```python\nfrom parameterizable.json_processor import access_jsparams\n\nsubset = access_jsparams(js2, \"n_trees\", \"depth\")\nassert subset == {\"n_trees\": 100, \"depth\": 5}\n```\n\n- Work with essential/auxiliary parameters:\n\n```python\nm.get_essential_params()      # {\"n_trees\": 50, \"depth\": 5}\nm.get_essential_jsparams()    # JSON string with only essential params\nm.get_auxiliary_params()      # {\"verbose\": True}\nm.get_auxiliary_jsparams()    # JSON string with only auxiliary params\n```\n\n- Sort dictionaries by keys (utility):\n\n```python\nfrom parameterizable.dict_sorter import sort_dict_by_keys\nsort_dict_by_keys({\"b\": 2, \"a\": 1})  # {\"a\": 1, \"b\": 2}\n```\n\n- Prevent pickling/unpickling using NotPicklableClass:\n\n```python\nimport pickle\nfrom parameterizable import NotPicklableClass\n\nclass Connection(NotPicklableClass):\n    pass\n\nconn = Connection()\n\n# Any attempt to pickle or unpickle will raise TypeError\ntry:\n    pickle.dumps(conn)\nexcept TypeError:\n    print(\"Connection cannot be pickled\")\n```\n\n## Development\n\n- Run tests:\n  - With pytest: `pytest`\n  - Or via Python: `python -m pytest`\n- Supported Python versions: 3.10+\n- See contributing guidelines: [contributing.md](contributing.md)\n\n## License\n\nThis project is licensed under the MIT License \u2014 see [LICENSE](LICENSE) for details.\n\n## Key Contacts\n\n* [Vlad (Volodymyr) Pavlov](https://www.linkedin.com/in/vlpavlov/)\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Library for work with parameterizable classes.",
    "version": "0.103.8",
    "project_urls": {
        "Docs": "https://parameterizable.readthedocs.io/",
        "Home": "https://github.com/pythagoras-dev/parameterizable"
    },
    "split_keywords": [
        "parameters"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "b1520c002afaffa3c5e7a0d9a63859dbd5c3b8886e5c1f38a4913f726a57518b",
                "md5": "571edaebf7868c2967dfda2bdba1f797",
                "sha256": "ea637218c9612f9be5b48512151877dbe1d5228402ae5afe7a6a26bf3f37e7a3"
            },
            "downloads": -1,
            "filename": "parameterizable-0.103.8-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "571edaebf7868c2967dfda2bdba1f797",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 13275,
            "upload_time": "2025-10-29T04:14:11",
            "upload_time_iso_8601": "2025-10-29T04:14:11.771757Z",
            "url": "https://files.pythonhosted.org/packages/b1/52/0c002afaffa3c5e7a0d9a63859dbd5c3b8886e5c1f38a4913f726a57518b/parameterizable-0.103.8-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "4524bcc719f41cac5012ade18878b8d80886380df798837eaa32bb1d7ea098aa",
                "md5": "d6d6c97e15781ed8271d94fdebbd679a",
                "sha256": "57a7157470914b675590ec7b4103dde6093eca06f5a5dabc3fbf938cd97ef764"
            },
            "downloads": -1,
            "filename": "parameterizable-0.103.8.tar.gz",
            "has_sig": false,
            "md5_digest": "d6d6c97e15781ed8271d94fdebbd679a",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 11033,
            "upload_time": "2025-10-29T04:14:12",
            "upload_time_iso_8601": "2025-10-29T04:14:12.954038Z",
            "url": "https://files.pythonhosted.org/packages/45/24/bcc719f41cac5012ade18878b8d80886380df798837eaa32bb1d7ea098aa/parameterizable-0.103.8.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-29 04:14:12",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "pythagoras-dev",
    "github_project": "parameterizable",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "parameterizable"
}
        
Elapsed time: 3.96898s