Basic Usage#

About#

In this section you can find a quickstart guide to serialix package, that will show you the basics of how this tool can be used. For more code examples you can see the examples directory on Github.

Quickstart#

serialix supports various data interchange languages (full list). This quickstart guide will be based on json format.

Imports#

Let’s import the main Serialix class from serialix package. This class was implemented in version 2.1.0 and should be used to create instance for any officially supported language.

1from serialix import Serialix

Note

Detailed Serialix documentation can be found here

Preparation#

Default values#

Next step we will define the default dictionary, that will be used later. Keys and values in it are absolutely random and meaningless 🙂.

2def_dict = {
3    "version": 5,
4    "app_name": "Test"
5}

Note

Specifying the default dictionary is optional and not required in your code, but this will allow us to specify values that will be written to a local file on creation and can be used for a “factory reset” feature later.

Parser Settings#

New in version 1.1.0.

Let’s also prepare some options for json parser

6parser_write_kwargs = {
7    "indent": 4
8}

parser_write_kwargs variable is dictionary with keyword arguments that will be further passed to arguments of Serialix object to specify the additional params for serialization language parser on write action. At this moment we will only include the indent argument for json parser, that will enable the pretty printing for output.

Creating Object#

Now we’re moving to the main part - creating an object that will be used for further interaction with the local file.

 6config = Serialix(
 7    'json',                                   # Name of the used format
 8    'settings.json',                          # Path to preferred local file location.
 9    def_dict,                                 # Default configuration dictionary that will
10                                              # be parsed into the local file on creation.
11    parser_write_kwargs = parser_write_kwargs # Arguments, that will be passed to parser on write action
12)

If no exceptions were raised then everything is ready. Now, if you check the file on the path, that we specified in line 3 of step Default values, you can see there’s a json format dictionary built from our def_dict.

{
    "version": 5,
    "app_name": "Test"
}

Note

If default_dictionary argument wasn’t specified on object initialization then the local file still will be created. Its content will depend on how each language handles storing an empty dictionary. In our case, local file will look like this:

{
}

New in version 1.2.0: You can also disable the automatic local file creation on object initialization by passing the keyword argument auto_file_creation=False to Serialix object.

Reading#

The local file and object are ready. Now we can access any value from this file. Let’s try this out:

13# Lets print the value of the key "version".
14# All keys can be directly accessed right from the object
15
16app_version = config["version"]                       # Getting the key 'version' from dictionary
17print("Application version: {}".format(app_version))  # Output should be:
18                                                      # 'Application version: 5'

Creating and modifying#

Accessing the values is a good thing, but we’re here not only for this, right? Next step we’ll modify the value of one exising key and add the new key to object.

19# Let's change the value of the key "app_name" to something new
20config["app_name"] = "Super Secret Tool"
21
22# And we'll also add the new key with dictionary value
23config["our_new_key"] = {
24    "type": "msg",
25    "id": 34724889325,
26    "text": "wassup?"
27}

Note

As you may already noticed, the way of interacting with serialix objects is quite same to dictionaries. That’s right, serialix provides quick access to the bound dictionary keys and methods. This dictionary contains the parsed from local file keys and values and can be directly accessed through .dictionary object property:

>>> config.dictionary
{'version': 5,
 'app_name': 'Super Secret Tool',
 'our_new_key': {'type': 'msg', 'id': 34724889325, 'text': 'wassup?'}}

Removing#

Now lets try to remove one key from dictionary. To remove any key you can use the python’s del() statement.

28# Let's delete the "text" key from our nested dictionary "our_new_key"
29del(config["our_new_key"]["text"])

Saving changes#

New key added, existing changed and even removed - but the local file still contains only the default values. It’s not a bug, it’s a feature. serialix will never automatically save any user-made changes to a local file without a direct command to do so. So let’s send it.

30# This method will commit all changes from object to local file
31config.commit()

Now our settings.json file will look like this:

{
    "version": 5,
    "app_name": "Super Secret Tool",
    "our_new_key": {
        "type": "msg",
        "id": 34724889325
    }
}

Refreshing from file#

Now let’s consider the situation that our local file (settings.json) was modified by some other application. serialix will never automatically refresh values of object, so you have to do it yourself.

Let’s modify the settings.json file with any text editor and add the new key "custom_key" with value "hello?". Now our local file will look like this:

{
    "version": 5,
    "app_name": "Super Secret Tool",
    "our_new_key": {
        "type": "msg",
        "id": 34724889325
    },
    "custom_key": "hello?"
}

To get this key inside of our config object we’ll have to refresh it with special method:

32# This method will refresh object's dictionary with dictionary parsed from the local file.
33config.refresh()
34
35# After refreshing, "custom_key" key will be added to object and can be accessed
36print(config["custom_key"])  # Output: 'hello?'

Note

In some cases you should better use the .reload() method instead. Refreshing with .refresh() will save the changes that already made to object and add the new one from local file, but this feature is much slower than simply reloading the file. Therefore, if you are sure that no uncommitted changes have been made to the object, it is better to use the .reload().

Factory Reset#

If you are not happy with all the changes made and want to return everything to the default state, here’s a method .reset_to_defaults()` specially for you. This method will reset bound dictionary to values from def_dict variable that we specified at the beginning of this guide.

37# Reset to bound dictionary to defaults
38config.reset_to_defaults()
39
40# And again, don't forget to commit the changes to local file
41config.commit()

Conclusion#

That’s it, now you’re ready for basic usage of serialix. Public API of this package is fully documented with docstrings, so you can get detailed information about any method, function, class, module or anything here