Skip to main content

Recursive Namespace. An extension of SimpleNamespace

Project description

RecursiveNamespace

Description

RecursiveNamespace is an extension of Python's SimpleNamespace that provides enhanced functionality for working with nested namespaces and dictionaries. This package allows easy access and manipulation of deeply nested data structures in an intuitive and Pythonic way.

Installation

To install RecursiveNamespace from PyPI use the following command.

pip install RecursiveNamespace

If you want to use the github clone, use the following.

git clone https://github.com/HessamLa/RecursiveNamespace.git
cd RecursiveNamespace
pip install .

Usage

The RecursiveNamespace class can be used in the same way as Python's SimpleNamespace class, but in a recursive fashion. The RecursiveNamespace class can be instantiated with a dictionary or keyword arguments. The RecursiveNamespace class also provides a to_dict() method that returns a dictionary representation of the namespace.

Basic Usage

One of the best use cases of this module is converting dict into a recursive namespace, and back to dict. Another usage is to convert a dictionary to a recursive namespace.

from recursivenamespace import rns # or RecursiveNamespace

data = {
    'name': 'John',
    'age': 30,
    'address': {
        'street': '123 Main St',
        'city': 'Anytown'
    },
    'friends': ['Jane', 'Tom']
}

rn = rns(data)
print(type(rn)) # <class 'recursivenamespace.main.recursivenamespace'>
print(rn)       # RNS(name=John, age=30, address=RNS(street=123 Main St, city=Anytown))
print(rn.name)  # John
print(rn.address.city) # Anytown
print(rn.friends[1])   # Tom, yes it does recognize iterables

# convert back to dictionary
data2 = rn.to_dict()
print(type(data2)) # <class 'dict'>
print(data2)       # {'name': 'John', 'age': 30, 'address': {'street': '123 Main St', 'city': 'Anytown'}}
print(data2['address']['city']) # Anytown
print(data2['friends'][1])      # Tom

You can use the key or namespace interchangeably

print(rn.friends[1] is rn['friends'][1]) # True

You can also use it with YAML.

import yaml
from recursivenamespace import rns
datatext = """
name: John
age: 30
address:
    street: 123 Main St
    city: Anytown
friends:
    - Jane
    - Tom
"""
data = yaml.safe_load(datatext)
rn = rns(data) 
print(rn) # RNS(name=John, age=30, address=RNS(street=123 Main St, city=Anytown))

# convert back to YAML
data_yaml = yaml.dump(rn.to_dict())

Let's see other use cases. You can make a nested rns.

from recursivenamespace import rns
results = rns(
    params=rns(
        alpha=1.0,
        beta=2.0,
    ),
    metrics=rns(
        accuracy=98.79,
        f1=97.62
    )
)

Access elements as dictionary keys or namespace attributes.

print(results.params.alpha is results.params['alpha'])             # True
print(results['metrics'].accuracy is  results.metrics['accuracy']) # True

Convert only the metrics to dictionary.

metrics_dict = results.metrics.to_dict()
print(metrics_dict) # {'accuracy': 98.79, 'f1': 97.62}

Or convert all to a nested dictionary.

from pprint import pprint
output_dict = results.to_dict()
pprint(output_dict)
# {'metrics': {'accuracy': 98.79, 'f1': 97.62},
# 'params':  {'alpha': 1.0, 'beta': 2.0}}

Flatten the dictionary using a separator for keys.

flat_dict = results.to_dict(flatten_sep='_')
pprint(flat_dict)
# {'metrics_accuracy': 98.79,
#  'metrics_f1': 97.62,
#  'params_alpha': 1.0,
#  'params_beta': 2.0}

Add more fields on the fly.

results.experiment_name = 'experiment_name'
results.params.dataset_version = 'dataset_version'
results.params.gamma = 0.35

The character '-' in a key will be converted to '_'

results.params['some-key'] = 'some-value'
print(results.params.some_key)                                  # some-value
print(results.params['some-key'] is results.params.some_key)    # True
print(results.params['some-key'] is results.params['some_key']) # True

Testing

To run tests, navigate to the project's root directory and execute:

python -m unittest discover tests

The test_recursive_namespace.py file contains tests for the RecursiveNamespace class.

Contributing

Contributions to the RecursiveNamespace project are welcome! Please ensure that any pull requests include tests covering new features or fixes.

License

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

You should copy the actual content from examlpes scripts (founde under ./examples/ directory) and paste it into the respective sections of the README. This provides users with immediate examples of how to use your package. The Testing section explains how to run the unit tests, encouraging users to check that everything is working correctly.

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

recursivenamespace-0.2.1.tar.gz (6.9 kB view details)

Uploaded Source

Built Distribution

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

RecursiveNamespace-0.2.1-py3-none-any.whl (6.8 kB view details)

Uploaded Python 3

File details

Details for the file recursivenamespace-0.2.1.tar.gz.

File metadata

  • Download URL: recursivenamespace-0.2.1.tar.gz
  • Upload date:
  • Size: 6.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.0 CPython/3.10.10

File hashes

Hashes for recursivenamespace-0.2.1.tar.gz
Algorithm Hash digest
SHA256 d8ec6f2104836bede421d2a96b14a37da022be218742a9a7f51ea4f641197b35
MD5 5698b6cc72eddd8d3c7d93efa3d60a0e
BLAKE2b-256 2d2d92ec79ebbecc98e90b63444bd3d67a453ec025047925f59d284bbe1cfba2

See more details on using hashes here.

File details

Details for the file RecursiveNamespace-0.2.1-py3-none-any.whl.

File metadata

File hashes

Hashes for RecursiveNamespace-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 f97657c30a9a78c13e6a19bb66f82d36b1a557ce24b9e86637d6ecc515558b19
MD5 7fd4d1f0afc7dd70cbfa8f187b74331b
BLAKE2b-256 db47839d495419e72e3f67c734c3e0745008852ac8494f946b7c77f4b6620b31

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