dicta


Namedicta JSON
Version 1.0.3 PyPI version JSON
download
home_page
SummaryA dict subclass to observe data changes in the nested data-tree.
upload_time2023-10-22 18:53:14
maintainer
docs_urlNone
author
requires_python>=3.8
licenseMIT License Copyright (c) 2023 Peter Wendl 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 callback dict fileimport json listener nested-objects serialization
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # dicta

A dict subclass that observes a nested dict and listens for changes in its data structure. If a data change is registered, Dicta reacts with a callback or a data-export to a JSON file.

## Core Functionality

- Detect data changes in a nested dict
- Throw a callback, when the nested data structure changes
- Write data to a JSON file, when the nested data structure changes
- Easily import & export JSON files to/from a nested dict

## Features

- Behaves like a regular `dict` and supports all `dict`, `list`, `tuple` and `set` methods.
- Supports nesting of all possible datatypes like `dict`, `list`, `tuple`, `set` and other objects like custom classes.
- Encodes non-serializable objects to a binary-string when writing data to a file (Optional / deactivated by default).
- Reading data from a file will decode a binary-string back to a non-serializable object (Optional / deactivated by default).
- Import/Insert additional data from json files.
- Export data to json files.


## Install

```
pip3 install dicta
```

## How to use

```python
import dicta

# Declare the 'Dicta' class.
dicta = dicta.Dicta()

# Activate binary serialization
dicta.setBinarySerializer(True)

# Set a synch file path.
dicta.synchFile("data.json")

# Define the callback method
def callback():
    print("Data changed!")
    print(dicta)

# Bind the callback method to dicta
dicta.bind(callback)

# Add data
dicta.importData({"key":"value"})
dicta.importData(key2=value2, key3=value3)
dicta["entities"] = {}
dicta["entities"]["persons"] = []

dicta["entities"]["persons"].append({"name":"john", "age":23})
dicta["entities"]["persons"].append({"name":"peter", "age":13})

# Update a key in a dict
dicta["entities"]["persons"][1]["age"] = 42

# Add another nested list to the dict
dicta["entities"]["animals"] = []
dicta["entities"]["animals"].append("lion")
dicta["entities"]["animals"].append("elephant")

# Slice item from list
del dicta["entities"]["animals"][0:1]

# Remove item from dict
dicta["entities"].pop("persons")

# and so forth…
# Should support all regular dict behaviours and 
# list methods (pop(), append(), slice(), insert() …)

# Import additional data from another file. 
# (New data will be added. Old data remains but will 
# be overwritten if dict keys match.)
dicta.importFile("additional_data_file.json")

# Export the data to another file
dicta.exportFile("data_backup.json")

# Get string representation of the Dicta
dicta.stringify()
```

## Reference

---

#### Dicta()

```python
Dicta(*args, **kwargs)
Dicta(dict)
Dicta(key=value,key2=value)
```

A dict subclass.

###### **Parameter**

- ***args** *(Optional)*
- ****kwargs** *(Optional)*

###### **Return**

- **Dicta Class**

---

### Methods

#### Dicta Methods

---

##### Dicta.bind()

```python
Dicta.bind(callback, response=False, *args, *kwargs)
```

Sets the callback method for the Dicta Class. If `response=False` (default) the callback method only gets the `*args, *kwargs` as parameters you define. If `response=True` the callback method gets response from the Dicta Class. You should define your callback function with a `*kwargs` parameter or with three positional parameters:

`def my_callback(**kwargs)`

or

`def my_callback(modifed_object, modify_info, modify_trace)`

###### **Parameter**

- **callback** *(method)*
- **default_response** *(bool) (optional / default = False)*

###### **Callback**

- **args** as defined in setCallback *(optional / default: None)*
- **kwargs** as defined in setCallback *(optional / default: None)*
- **modifed_object** *(object)*
- ***modify_info*** *(json_string)*: Contains info about the data mod
- **modify_trace** *(list)*: Contains the dict-tree-path to the modified object as a list starting from root*

---

##### Dicta.syncFile()

```python
Dicta.syncFile(path, reset=False)
```

Sets the sync file to automatically store the data on data change. If `reset=False` (default) old data will remain and will be updated with new data . If `reset=True` the data wil be cleared when `syncFile()` is called.

**This will fail if your dict contains non-serializable objects and binary serialization is not activated.** For security reasons this is deactivated by default. You can activate binary serialization manually with `Dicta.useBinarySerializer(True)`.

If you activate the binary-serializer all non-serializable objects will be encoded to a binary string and packed into a `dict` labeled with the key `'<serialized-object>'`. See the reference for `Dicta.useBinarySerializer()`.

###### **Parameter**

- **path** *(string)*
- **reset** *(bool) (optional / default = False)*

---

##### Dicta.importFile()

```python
Dicta.importFile(path)
```

Import data from a file. New data will be added to the DictObsercer, old data remains but will be overwritten if dict keys match.

###### **Parameter**

- **path** *(string)*

---

##### Dicta.exportFile()

```python
Dicta.exportFile(path, reset=True)
```

Export data to a file. If `reset=True` the data wil be cleared when `exportFile()` (default) is called . If `reset=False` the data will be updated.

**This will fail if your dict contains non-serializable objects and binary serialization is not activated.** For security reasons this is deactivated by default. You can activate binary serialization by calling `Dicta.useBinarySerializer(True)` before.

If you activate the binary-serializer all non-serializable objects will be encoded to a binary string and packed into a `dict` labeled with the key `'<serialized-object>'`. See the reference for `Dicta.useBinarySerializer()`.

###### **Parameter**

- **path** (string)
- **reset** *(bool) (optional / default = True)*

---

##### Dicta.clearFile()

```python
Dicta.clearFile(path)
```

Clear a file.

###### **Parameter**

- **path** *(string)*

---

##### Dicta.removeFile()

```python
Dicta.removeFile(path)
```

Remove a data file.

###### **Parameter**

- **path** *(string)*

---

##### Dicta.importData(*args,**kwargs)

```python
Dicta.importData(dict)
Dicta.importData(key=value,key2=value2…)
```

Import data as dict or key/value pairs.

---

##### Dicta.dictify()

```python
Dicta.dictify()
```

Returns a plain dict representation of the data without Dicta functionality.

###### **Parameter**

- None

###### **Return**

- **dict**

---

##### Dicta.stringify()

```python
Dicta.stringify(returnBinaries=False)
```

Returns a string representation of the data in Dicta.

**This will fail if your dict contains non-serializable objects and binary serialization is not activated.** For security reasons this is deactivated by default. You can activate binary serialization by calling `Dicta.useBinarySerializer(True)` before.

If you activate the binary-serializer all non-serializable objects will be encoded to a binary string and packed into a `dict` labeled with the key `'<serialized-object>'`. See the reference for `Dicta.useBinarySerializer()`.

For better readability serialized objects won´t be returned by default and are replaced by a the `'<serialized-object>'` hook. If you want to return the binaries set the `return_binaries`parameter to `True`.

###### **Parameter**

- **return_binaries** *(bool) (default = False)*

###### **Return**

- **string**

---

##### Dicta.setBinarySerializer()

```python
Dicta.setBinarySerializer(binary_serializer=False, serializer_hook='<serialized-object>')
```

For security reasons binary serialization of non-serializable objects is deactivated by default. You can activate or deactivate binary serialization with this method (default=False).

If you activate the binary-serializer all non-serializable objects will be encoded to a binary string and packed into a dict labeled with the key `'<serialized-object>'`. In case you need this key for your data structure, define a custom serializer-hook by using the `serializer_hook` parameter (optional). If you don´t use the `serializer_hook` parameter the default hook `'<serialized-object>'` will be used.

###### Parameter

- **binary_serializer** *(bool) (default = False)*
- **serializer_hook** *(string) (optional / default = '\<serialized-object>')*

###### Example

```python
myDicta.setBinarySerializer(True)
myDicta.setBinarySerializer(True, '<my_serialzer_hook>')
```

---

#### Data Type Methods

Behaves like a regular nested dict and supports all data type methods. Adding, removing, modifiying and accessing of nested elements should work out of the box. For example:

---

##### NestedDict.update()

```python
NestedDict.update(*args, *kwargs)
```

---

##### NestedDict.clear()

```python
NestedDict.clear()
```

---

##### NestedDict.pop()

```python
NestedDict.pop(key)
```

---

##### NestedDict.popitem()

```python
NestedDict.popitem(key)
```

---

##### NestedDict.setdefault()

```python
NestedDict.setdefault(key, default=None)
```

*and so forth: keys(), iter() …*

---

##### NestedList.append()

```python
NestedList.append(item)
```

*and so forth: pop()…*

---

## Dependencies

- os
- re
- json
- pickle

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "dicta",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "",
    "keywords": "callback,dict,fileimport,json,listener,nested-objects,serialization",
    "author": "",
    "author_email": "Peter Wendl <dev@peterwendl.de>",
    "download_url": "https://files.pythonhosted.org/packages/36/a5/32cb3e64f796ad125dc6feb580932cbec56ee5fb5c2caabc9fe77086c890/dicta-1.0.3.tar.gz",
    "platform": null,
    "description": "# dicta\n\nA dict subclass that observes a nested dict and listens for changes in its data structure. If a data change is registered, Dicta reacts with a callback or a data-export to a JSON file.\n\n## Core Functionality\n\n- Detect data changes in a nested dict\n- Throw a callback, when the nested data structure changes\n- Write data to a JSON file, when the nested data structure changes\n- Easily import & export JSON files to/from a nested dict\n\n## Features\n\n- Behaves like a regular `dict` and supports all `dict`, `list`, `tuple` and `set` methods.\n- Supports nesting of all possible datatypes like `dict`, `list`, `tuple`, `set` and other objects like custom classes.\n- Encodes non-serializable objects to a binary-string when writing data to a file (Optional / deactivated by default).\n- Reading data from a file will decode a binary-string back to a non-serializable object (Optional / deactivated by default).\n- Import/Insert additional data from json files.\n- Export data to json files.\n\n\n## Install\n\n```\npip3 install dicta\n```\n\n## How to use\n\n```python\nimport dicta\n\n# Declare the 'Dicta' class.\ndicta = dicta.Dicta()\n\n# Activate binary serialization\ndicta.setBinarySerializer(True)\n\n# Set a synch file path.\ndicta.synchFile(\"data.json\")\n\n# Define the callback method\ndef callback():\n    print(\"Data changed!\")\n    print(dicta)\n\n# Bind the callback method to dicta\ndicta.bind(callback)\n\n# Add data\ndicta.importData({\"key\":\"value\"})\ndicta.importData(key2=value2, key3=value3)\ndicta[\"entities\"] = {}\ndicta[\"entities\"][\"persons\"] = []\n\ndicta[\"entities\"][\"persons\"].append({\"name\":\"john\", \"age\":23})\ndicta[\"entities\"][\"persons\"].append({\"name\":\"peter\", \"age\":13})\n\n# Update a key in a dict\ndicta[\"entities\"][\"persons\"][1][\"age\"] = 42\n\n# Add another nested list to the dict\ndicta[\"entities\"][\"animals\"] = []\ndicta[\"entities\"][\"animals\"].append(\"lion\")\ndicta[\"entities\"][\"animals\"].append(\"elephant\")\n\n# Slice item from list\ndel dicta[\"entities\"][\"animals\"][0:1]\n\n# Remove item from dict\ndicta[\"entities\"].pop(\"persons\")\n\n# and so forth\u2026\n# Should support all regular dict behaviours and \n# list methods (pop(), append(), slice(), insert() \u2026)\n\n# Import additional data from another file. \n# (New data will be added. Old data remains but will \n# be overwritten if dict keys match.)\ndicta.importFile(\"additional_data_file.json\")\n\n# Export the data to another file\ndicta.exportFile(\"data_backup.json\")\n\n# Get string representation of the Dicta\ndicta.stringify()\n```\n\n## Reference\n\n---\n\n#### Dicta()\n\n```python\nDicta(*args, **kwargs)\nDicta(dict)\nDicta(key=value,key2=value)\n```\n\nA dict subclass.\n\n###### **Parameter**\n\n- ***args** *(Optional)*\n- ****kwargs** *(Optional)*\n\n###### **Return**\n\n- **Dicta Class**\n\n---\n\n### Methods\n\n#### Dicta Methods\n\n---\n\n##### Dicta.bind()\n\n```python\nDicta.bind(callback, response=False, *args, *kwargs)\n```\n\nSets the callback method for the Dicta Class. If `response=False` (default) the callback method only gets the `*args, *kwargs` as parameters you define. If `response=True` the callback method gets response from the Dicta Class. You should define your callback function with a `*kwargs` parameter or with three positional parameters:\n\n`def my_callback(**kwargs)`\n\nor\n\n`def my_callback(modifed_object, modify_info, modify_trace)`\n\n###### **Parameter**\n\n- **callback** *(method)*\n- **default_response** *(bool) (optional / default = False)*\n\n###### **Callback**\n\n- **args** as defined in setCallback *(optional / default: None)*\n- **kwargs** as defined in setCallback *(optional / default: None)*\n- **modifed_object** *(object)*\n- ***modify_info*** *(json_string)*: Contains info about the data mod\n- **modify_trace** *(list)*: Contains the dict-tree-path to the modified object as a list starting from root*\n\n---\n\n##### Dicta.syncFile()\n\n```python\nDicta.syncFile(path, reset=False)\n```\n\nSets the sync file to automatically store the data on data change. If `reset=False` (default) old data will remain and will be updated with new data . If `reset=True` the data wil be cleared when `syncFile()` is called.\n\n**This will fail if your dict contains non-serializable objects and binary serialization is not activated.** For security reasons this is deactivated by default. You can activate binary serialization manually with `Dicta.useBinarySerializer(True)`.\n\nIf you activate the binary-serializer all non-serializable objects will be encoded to a binary string and packed into a `dict` labeled with the key `'<serialized-object>'`. See the reference for `Dicta.useBinarySerializer()`.\n\n###### **Parameter**\n\n- **path** *(string)*\n- **reset** *(bool) (optional / default = False)*\n\n---\n\n##### Dicta.importFile()\n\n```python\nDicta.importFile(path)\n```\n\nImport data from a file. New data will be added to the DictObsercer, old data remains but will be overwritten if dict keys match.\n\n###### **Parameter**\n\n- **path** *(string)*\n\n---\n\n##### Dicta.exportFile()\n\n```python\nDicta.exportFile(path, reset=True)\n```\n\nExport data to a file. If `reset=True` the data wil be cleared when `exportFile()` (default) is called . If `reset=False` the data will be updated.\n\n**This will fail if your dict contains non-serializable objects and binary serialization is not activated.** For security reasons this is deactivated by default. You can activate binary serialization by calling `Dicta.useBinarySerializer(True)` before.\n\nIf you activate the binary-serializer all non-serializable objects will be encoded to a binary string and packed into a `dict` labeled with the key `'<serialized-object>'`. See the reference for `Dicta.useBinarySerializer()`.\n\n###### **Parameter**\n\n- **path** (string)\n- **reset** *(bool) (optional / default = True)*\n\n---\n\n##### Dicta.clearFile()\n\n```python\nDicta.clearFile(path)\n```\n\nClear a file.\n\n###### **Parameter**\n\n- **path** *(string)*\n\n---\n\n##### Dicta.removeFile()\n\n```python\nDicta.removeFile(path)\n```\n\nRemove a data file.\n\n###### **Parameter**\n\n- **path** *(string)*\n\n---\n\n##### Dicta.importData(*args,**kwargs)\n\n```python\nDicta.importData(dict)\nDicta.importData(key=value,key2=value2\u2026)\n```\n\nImport data as dict or key/value pairs.\n\n---\n\n##### Dicta.dictify()\n\n```python\nDicta.dictify()\n```\n\nReturns a plain dict representation of the data without Dicta functionality.\n\n###### **Parameter**\n\n- None\n\n###### **Return**\n\n- **dict**\n\n---\n\n##### Dicta.stringify()\n\n```python\nDicta.stringify(returnBinaries=False)\n```\n\nReturns a string representation of the data in Dicta.\n\n**This will fail if your dict contains non-serializable objects and binary serialization is not activated.** For security reasons this is deactivated by default. You can activate binary serialization by calling `Dicta.useBinarySerializer(True)` before.\n\nIf you activate the binary-serializer all non-serializable objects will be encoded to a binary string and packed into a `dict` labeled with the key `'<serialized-object>'`. See the reference for `Dicta.useBinarySerializer()`.\n\nFor better readability serialized objects won\u00b4t be returned by default and are replaced by a the `'<serialized-object>'` hook. If you want to return the binaries set the `return_binaries`parameter to `True`.\n\n###### **Parameter**\n\n- **return_binaries** *(bool) (default = False)*\n\n###### **Return**\n\n- **string**\n\n---\n\n##### Dicta.setBinarySerializer()\n\n```python\nDicta.setBinarySerializer(binary_serializer=False, serializer_hook='<serialized-object>')\n```\n\nFor security reasons binary serialization of non-serializable objects is deactivated by default. You can activate or deactivate binary serialization with this method (default=False).\n\nIf you activate the binary-serializer all non-serializable objects will be encoded to a binary string and packed into a dict labeled with the key `'<serialized-object>'`. In case you need this key for your data structure, define a custom serializer-hook by using the `serializer_hook` parameter (optional). If you don\u00b4t use the `serializer_hook` parameter the default hook `'<serialized-object>'` will be used.\n\n###### Parameter\n\n- **binary_serializer** *(bool) (default = False)*\n- **serializer_hook** *(string) (optional / default = '\\<serialized-object>')*\n\n###### Example\n\n```python\nmyDicta.setBinarySerializer(True)\nmyDicta.setBinarySerializer(True, '<my_serialzer_hook>')\n```\n\n---\n\n#### Data Type Methods\n\nBehaves like a regular nested dict and supports all data type methods. Adding, removing, modifiying and accessing of nested elements should work out of the box. For example:\n\n---\n\n##### NestedDict.update()\n\n```python\nNestedDict.update(*args, *kwargs)\n```\n\n---\n\n##### NestedDict.clear()\n\n```python\nNestedDict.clear()\n```\n\n---\n\n##### NestedDict.pop()\n\n```python\nNestedDict.pop(key)\n```\n\n---\n\n##### NestedDict.popitem()\n\n```python\nNestedDict.popitem(key)\n```\n\n---\n\n##### NestedDict.setdefault()\n\n```python\nNestedDict.setdefault(key, default=None)\n```\n\n*and so forth: keys(), iter() \u2026*\n\n---\n\n##### NestedList.append()\n\n```python\nNestedList.append(item)\n```\n\n*and so forth: pop()\u2026*\n\n---\n\n## Dependencies\n\n- os\n- re\n- json\n- pickle\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2023 Peter Wendl  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 dict subclass to observe data changes in the nested data-tree.",
    "version": "1.0.3",
    "project_urls": {
        "Homepage": "https://github.com/mextex/dicta"
    },
    "split_keywords": [
        "callback",
        "dict",
        "fileimport",
        "json",
        "listener",
        "nested-objects",
        "serialization"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b315b7a40c72e920f182ab36c7c2a6942ce594e4cb999a75fc0a82156d30d017",
                "md5": "7d61748bfd0dc2f08ae119d897e02e98",
                "sha256": "238e1190fb348c121dcb5c15ffb6aee8c2c8afa0cb705ced10ee55eda787812b"
            },
            "downloads": -1,
            "filename": "dicta-1.0.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "7d61748bfd0dc2f08ae119d897e02e98",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 9950,
            "upload_time": "2023-10-22T18:53:13",
            "upload_time_iso_8601": "2023-10-22T18:53:13.368405Z",
            "url": "https://files.pythonhosted.org/packages/b3/15/b7a40c72e920f182ab36c7c2a6942ce594e4cb999a75fc0a82156d30d017/dicta-1.0.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "36a532cb3e64f796ad125dc6feb580932cbec56ee5fb5c2caabc9fe77086c890",
                "md5": "509f486dba8c01bb96fab0693f964083",
                "sha256": "b12843c971990baece076445649060391a0f3cdb59fdaf66584a31c486acd8d1"
            },
            "downloads": -1,
            "filename": "dicta-1.0.3.tar.gz",
            "has_sig": false,
            "md5_digest": "509f486dba8c01bb96fab0693f964083",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 10354,
            "upload_time": "2023-10-22T18:53:14",
            "upload_time_iso_8601": "2023-10-22T18:53:14.828944Z",
            "url": "https://files.pythonhosted.org/packages/36/a5/32cb3e64f796ad125dc6feb580932cbec56ee5fb5c2caabc9fe77086c890/dicta-1.0.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-10-22 18:53:14",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "mextex",
    "github_project": "dicta",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "dicta"
}
        
Elapsed time: 0.13009s