Gitlab - Argos ALM by PALO IT

feat: dict-mapper lib

transforms the structure of a dictionary based on a given set of transformation rules
parent 7887b3a4
# Created by https://www.toptal.com/developers/gitignore/api/python,visualstudiocode,pycharm
# Edit at https://www.toptal.com/developers/gitignore?templates=python,visualstudiocode,pycharm
### PyCharm ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### PyCharm Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
# https://plugins.jetbrains.com/plugin/7973-sonarlint
.idea/**/sonarlint/
# SonarQube Plugin
# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin
.idea/**/sonarIssues.xml
# Markdown Navigator plugin
# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced
.idea/**/markdown-navigator.xml
.idea/**/markdown-navigator-enh.xml
.idea/**/markdown-navigator/
# Cache file creation bug
# See https://youtrack.jetbrains.com/issue/JBR-2257
.idea/$CACHE_FILE$
# CodeStream plugin
# https://plugins.jetbrains.com/plugin/12206-codestream
.idea/codestream.xml
# Azure Toolkit for IntelliJ plugin
# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij
.idea/**/azureSettings.xml
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
### Python Patch ###
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
poetry.toml
# ruff
.ruff_cache/
# LSP config files
pyrightconfig.json
### VisualStudioCode ###
.vscode/
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
### VisualStudioCode Patch ###
# Ignore all local history of files
.history
.ionide
# End of https://www.toptal.com/developers/gitignore/api/python,visualstudiocode,pycharm
\ No newline at end of file
# dict-mapper
Dict-Mapper library provides a flexible and powerful way to transform the structure of a dictionary based on a given set
of transformation rules. This can be particularly useful when you need to reshape data to fit a specific structure or
format.
## Features
The main function in this module is `map_dict(original:)`, which takes an original dictionary and a specification
dictionary as
inputs, and returns a new dictionary that has been transformed according to the specification.
The specification dictionary defines how the original dictionary should be transformed. Its keys are the keys of the new
dictionary, and its values can be:
- A string representing the key in the original dictionary.
- An instance of the 'skip' class to indicate that the key should be omitted.
- A function that takes the original dictionary and returns a value.
## Quick Start
````python
import uuid
from dict_mapper.mapping import map_dict, calculate_from_original, factory, skip
original = {"first_name": "Mac", "last_name": "Doe", "age": 30, "dob": "1990-01-01"}
specification = {
"id": factory(lambda: str(uuid.uuid4())),
"first_name": skip(),
"last_name": skip(),
"full_name": calculate_from_original(
lambda d: d["first_name"] + " " + d["last_name"]
),
}
result = map_dict(original, specification, keep_unmapped=True)
print(result)
"""
{
"age": 30,
"dob": "1990-01-01",
"id": "160281d4-a243-46b1-b3ac-23e7de7eb178",
"full_name": "Mac Doe",
}
"""
````
## Usage
```python
import uuid
from datetime import date, datetime
from dict_mapper.mapping import (
calculate_from_key,
calculate_from_original,
constant,
date_today,
datetime_now,
factory,
map_dict,
or_default,
with_type,
skip,
)
original = {
"first_name": "Mac",
"last_name": "Doe",
"age": 30,
"dob": "1990-01-01",
"address": {
"street": "127 Manuel Fernando de Soto",
"suburb": "Ciudad de México",
"postcode": "07469",
},
}
specification = {
"id": factory(lambda: str(uuid.uuid4())),
"status": constant("ACTIVE"),
"start_date": or_default("start_date", default=date.today()),
"created_at": datetime_now(),
"first_name": skip(),
"last_name": skip(),
"full_name": calculate_from_original(
lambda d: d["first_name"] + " " + d["last_name"]
),
"day_of_birth": with_type("dob", rtype=date),
"home_address": "address",
"home_address.suburb": skip(),
"home_address.country.code": skip(),
}
result = map_dict(original, specification, keep_unmapped=True)
print(result)
"""
{
"age": 30,
"dob": "1990-01-01",
"address": {
> "street": "127 Manuel Fernando de Soto",
"suburb": "Ciudad de México",
"postcode": "07469",
},
"id": "77e7e267-f3fa-4a94-9f2b-d1e98c135a8c",
"status": "ACTIVE",
"start_date": datetime.date(2024, 4, 11),
"created_at": datetime.datetime(2024, 4, 11, 20, 57, 35, 91853),
"full_name": "Mac Doe",
"day_of_birth": datetime.date(1990, 1, 1),
"home_address": {"street": "127 Manuel Fernando de Soto", "postcode": "07469"},
}
"""
```
In this example, the `map_dict()` function is used to create a new dictionary from the `original` dictionary.
The `specification` dictionary defines how the original dictionary should be transformed.
The `first_name` and `last_name` keys are removed from the result, a new `full_name` key is calculated from the original
dictionary, and the `address` key is renamed to `home_address` in the new dictionary. The `keep_unmapped` parameter is
set to `True`, so all keys in the original dictionary that are not in the specification are kept in the new dictionary.
The `key` names of the `specification` will be used as the keys in the new dictionary. The values of the `specification`
are used to know from where take the value for the new dictionary. The values can be a string representing the key in
the original dictionary, an instance of the `skip` class to indicate that the key should be omitted, or a function that
takes the original dictionary and returns a new value.
The library provides several helper functions that can be used in the specification dictionary:
- `constant(value)`: Assigns the given value to the given specification key.
- `or_default(key:str, default)`: Assigns the value of the key in the dictionary or the default value if the key is not
present.
- `calculate_from_original(func)`: Applies the given function to the original dictionary and assigns the result to the
given key.
- `calculate_from_key(key:str, transform, default=None)`: Applies the transform function to the value of the key in the
dictionary and assigns the result to the given key.
- `factory(func)`: Applies the function with no arguments and assigns the result to the given key. Useful for generating
unique IDs or initialize objects such as list or dict.
- `datetime_now()`: Assigns the current datetime in the given key.
- `date_today()`: Assigns the current date in the given key.
- `with_type(key:str: str, rtype: Type[Any], default=None, _format: str = None)`: Applies a str to bool,date,datetime
conversion to the value of the key in the dictionary to the given type.
\ No newline at end of file
# This file is automatically @generated by Poetry 1.7.1 and should not be changed by hand.
[[package]]
name = "black"
version = "24.3.0"
description = "The uncompromising code formatter."
optional = false
python-versions = ">=3.8"
files = [
{file = "black-24.3.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:7d5e026f8da0322b5662fa7a8e752b3fa2dac1c1cbc213c3d7ff9bdd0ab12395"},
{file = "black-24.3.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9f50ea1132e2189d8dff0115ab75b65590a3e97de1e143795adb4ce317934995"},
{file = "black-24.3.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e2af80566f43c85f5797365077fb64a393861a3730bd110971ab7a0c94e873e7"},
{file = "black-24.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:4be5bb28e090456adfc1255e03967fb67ca846a03be7aadf6249096100ee32d0"},
{file = "black-24.3.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4f1373a7808a8f135b774039f61d59e4be7eb56b2513d3d2f02a8b9365b8a8a9"},
{file = "black-24.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:aadf7a02d947936ee418777e0247ea114f78aff0d0959461057cae8a04f20597"},
{file = "black-24.3.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:65c02e4ea2ae09d16314d30912a58ada9a5c4fdfedf9512d23326128ac08ac3d"},
{file = "black-24.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:bf21b7b230718a5f08bd32d5e4f1db7fc8788345c8aea1d155fc17852b3410f5"},
{file = "black-24.3.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:2818cf72dfd5d289e48f37ccfa08b460bf469e67fb7c4abb07edc2e9f16fb63f"},
{file = "black-24.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4acf672def7eb1725f41f38bf6bf425c8237248bb0804faa3965c036f7672d11"},
{file = "black-24.3.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c7ed6668cbbfcd231fa0dc1b137d3e40c04c7f786e626b405c62bcd5db5857e4"},
{file = "black-24.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:56f52cfbd3dabe2798d76dbdd299faa046a901041faf2cf33288bc4e6dae57b5"},
{file = "black-24.3.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:79dcf34b33e38ed1b17434693763301d7ccbd1c5860674a8f871bd15139e7837"},
{file = "black-24.3.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:e19cb1c6365fd6dc38a6eae2dcb691d7d83935c10215aef8e6c38edee3f77abd"},
{file = "black-24.3.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:65b76c275e4c1c5ce6e9870911384bff5ca31ab63d19c76811cb1fb162678213"},
{file = "black-24.3.0-cp38-cp38-win_amd64.whl", hash = "sha256:b5991d523eee14756f3c8d5df5231550ae8993e2286b8014e2fdea7156ed0959"},
{file = "black-24.3.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:c45f8dff244b3c431b36e3224b6be4a127c6aca780853574c00faf99258041eb"},
{file = "black-24.3.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:6905238a754ceb7788a73f02b45637d820b2f5478b20fec82ea865e4f5d4d9f7"},
{file = "black-24.3.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d7de8d330763c66663661a1ffd432274a2f92f07feeddd89ffd085b5744f85e7"},
{file = "black-24.3.0-cp39-cp39-win_amd64.whl", hash = "sha256:7bb041dca0d784697af4646d3b62ba4a6b028276ae878e53f6b4f74ddd6db99f"},
{file = "black-24.3.0-py3-none-any.whl", hash = "sha256:41622020d7120e01d377f74249e677039d20e6344ff5851de8a10f11f513bf93"},
{file = "black-24.3.0.tar.gz", hash = "sha256:a0c9c4a0771afc6919578cec71ce82a3e31e054904e7197deacbc9382671c41f"},
]
[package.dependencies]
click = ">=8.0.0"
mypy-extensions = ">=0.4.3"
packaging = ">=22.0"
pathspec = ">=0.9.0"
platformdirs = ">=2"
[package.extras]
colorama = ["colorama (>=0.4.3)"]
d = ["aiohttp (>=3.7.4)", "aiohttp (>=3.7.4,!=3.9.0)"]
jupyter = ["ipython (>=7.8.0)", "tokenize-rt (>=3.2.0)"]
uvloop = ["uvloop (>=0.15.2)"]
[[package]]
name = "click"
version = "8.1.7"
description = "Composable command line interface toolkit"
optional = false
python-versions = ">=3.7"
files = [
{file = "click-8.1.7-py3-none-any.whl", hash = "sha256:ae74fb96c20a0277a1d615f1e4d73c8414f5a98db8b799a7931d1582f3390c28"},
{file = "click-8.1.7.tar.gz", hash = "sha256:ca9853ad459e787e2192211578cc907e7594e294c7ccc834310722b41b9ca6de"},
]
[package.dependencies]
colorama = {version = "*", markers = "platform_system == \"Windows\""}
[[package]]
name = "colorama"
version = "0.4.6"
description = "Cross-platform colored terminal text."
optional = false
python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7"
files = [
{file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"},
{file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"},
]
[[package]]
name = "coverage"
version = "7.4.4"
description = "Code coverage measurement for Python"
optional = false
python-versions = ">=3.8"
files = [
{file = "coverage-7.4.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:e0be5efd5127542ef31f165de269f77560d6cdef525fffa446de6f7e9186cfb2"},
{file = "coverage-7.4.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:ccd341521be3d1b3daeb41960ae94a5e87abe2f46f17224ba5d6f2b8398016cf"},
{file = "coverage-7.4.4-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:09fa497a8ab37784fbb20ab699c246053ac294d13fc7eb40ec007a5043ec91f8"},
{file = "coverage-7.4.4-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b1a93009cb80730c9bca5d6d4665494b725b6e8e157c1cb7f2db5b4b122ea562"},
{file = "coverage-7.4.4-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:690db6517f09336559dc0b5f55342df62370a48f5469fabf502db2c6d1cffcd2"},
{file = "coverage-7.4.4-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:09c3255458533cb76ef55da8cc49ffab9e33f083739c8bd4f58e79fecfe288f7"},
{file = "coverage-7.4.4-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:8ce1415194b4a6bd0cdcc3a1dfbf58b63f910dcb7330fe15bdff542c56949f87"},
{file = "coverage-7.4.4-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:b91cbc4b195444e7e258ba27ac33769c41b94967919f10037e6355e998af255c"},
{file = "coverage-7.4.4-cp310-cp310-win32.whl", hash = "sha256:598825b51b81c808cb6f078dcb972f96af96b078faa47af7dfcdf282835baa8d"},
{file = "coverage-7.4.4-cp310-cp310-win_amd64.whl", hash = "sha256:09ef9199ed6653989ebbcaacc9b62b514bb63ea2f90256e71fea3ed74bd8ff6f"},
{file = "coverage-7.4.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0f9f50e7ef2a71e2fae92774c99170eb8304e3fdf9c8c3c7ae9bab3e7229c5cf"},
{file = "coverage-7.4.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:623512f8ba53c422fcfb2ce68362c97945095b864cda94a92edbaf5994201083"},
{file = "coverage-7.4.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0513b9508b93da4e1716744ef6ebc507aff016ba115ffe8ecff744d1322a7b63"},
{file = "coverage-7.4.4-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:40209e141059b9370a2657c9b15607815359ab3ef9918f0196b6fccce8d3230f"},
{file = "coverage-7.4.4-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8a2b2b78c78293782fd3767d53e6474582f62443d0504b1554370bde86cc8227"},
{file = "coverage-7.4.4-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:73bfb9c09951125d06ee473bed216e2c3742f530fc5acc1383883125de76d9cd"},
{file = "coverage-7.4.4-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:1f384c3cc76aeedce208643697fb3e8437604b512255de6d18dae3f27655a384"},
{file = "coverage-7.4.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:54eb8d1bf7cacfbf2a3186019bcf01d11c666bd495ed18717162f7eb1e9dd00b"},
{file = "coverage-7.4.4-cp311-cp311-win32.whl", hash = "sha256:cac99918c7bba15302a2d81f0312c08054a3359eaa1929c7e4b26ebe41e9b286"},
{file = "coverage-7.4.4-cp311-cp311-win_amd64.whl", hash = "sha256:b14706df8b2de49869ae03a5ccbc211f4041750cd4a66f698df89d44f4bd30ec"},
{file = "coverage-7.4.4-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:201bef2eea65e0e9c56343115ba3814e896afe6d36ffd37bab783261db430f76"},
{file = "coverage-7.4.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:41c9c5f3de16b903b610d09650e5e27adbfa7f500302718c9ffd1c12cf9d6818"},
{file = "coverage-7.4.4-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d898fe162d26929b5960e4e138651f7427048e72c853607f2b200909794ed978"},
{file = "coverage-7.4.4-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3ea79bb50e805cd6ac058dfa3b5c8f6c040cb87fe83de10845857f5535d1db70"},
{file = "coverage-7.4.4-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ce4b94265ca988c3f8e479e741693d143026632672e3ff924f25fab50518dd51"},
{file = "coverage-7.4.4-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:00838a35b882694afda09f85e469c96367daa3f3f2b097d846a7216993d37f4c"},
{file = "coverage-7.4.4-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:fdfafb32984684eb03c2d83e1e51f64f0906b11e64482df3c5db936ce3839d48"},
{file = "coverage-7.4.4-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:69eb372f7e2ece89f14751fbcbe470295d73ed41ecd37ca36ed2eb47512a6ab9"},
{file = "coverage-7.4.4-cp312-cp312-win32.whl", hash = "sha256:137eb07173141545e07403cca94ab625cc1cc6bc4c1e97b6e3846270e7e1fea0"},
{file = "coverage-7.4.4-cp312-cp312-win_amd64.whl", hash = "sha256:d71eec7d83298f1af3326ce0ff1d0ea83c7cb98f72b577097f9083b20bdaf05e"},
{file = "coverage-7.4.4-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:d5ae728ff3b5401cc320d792866987e7e7e880e6ebd24433b70a33b643bb0384"},
{file = "coverage-7.4.4-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:cc4f1358cb0c78edef3ed237ef2c86056206bb8d9140e73b6b89fbcfcbdd40e1"},
{file = "coverage-7.4.4-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8130a2aa2acb8788e0b56938786c33c7c98562697bf9f4c7d6e8e5e3a0501e4a"},
{file = "coverage-7.4.4-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cf271892d13e43bc2b51e6908ec9a6a5094a4df1d8af0bfc360088ee6c684409"},
{file = "coverage-7.4.4-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a4cdc86d54b5da0df6d3d3a2f0b710949286094c3a6700c21e9015932b81447e"},
{file = "coverage-7.4.4-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:ae71e7ddb7a413dd60052e90528f2f65270aad4b509563af6d03d53e979feafd"},
{file = "coverage-7.4.4-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:38dd60d7bf242c4ed5b38e094baf6401faa114fc09e9e6632374388a404f98e7"},
{file = "coverage-7.4.4-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:aa5b1c1bfc28384f1f53b69a023d789f72b2e0ab1b3787aae16992a7ca21056c"},
{file = "coverage-7.4.4-cp38-cp38-win32.whl", hash = "sha256:dfa8fe35a0bb90382837b238fff375de15f0dcdb9ae68ff85f7a63649c98527e"},
{file = "coverage-7.4.4-cp38-cp38-win_amd64.whl", hash = "sha256:b2991665420a803495e0b90a79233c1433d6ed77ef282e8e152a324bbbc5e0c8"},
{file = "coverage-7.4.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:3b799445b9f7ee8bf299cfaed6f5b226c0037b74886a4e11515e569b36fe310d"},
{file = "coverage-7.4.4-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:b4d33f418f46362995f1e9d4f3a35a1b6322cb959c31d88ae56b0298e1c22357"},
{file = "coverage-7.4.4-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aadacf9a2f407a4688d700e4ebab33a7e2e408f2ca04dbf4aef17585389eff3e"},
{file = "coverage-7.4.4-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7c95949560050d04d46b919301826525597f07b33beba6187d04fa64d47ac82e"},
{file = "coverage-7.4.4-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ff7687ca3d7028d8a5f0ebae95a6e4827c5616b31a4ee1192bdfde697db110d4"},
{file = "coverage-7.4.4-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:5fc1de20b2d4a061b3df27ab9b7c7111e9a710f10dc2b84d33a4ab25065994ec"},
{file = "coverage-7.4.4-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:c74880fc64d4958159fbd537a091d2a585448a8f8508bf248d72112723974cbd"},
{file = "coverage-7.4.4-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:742a76a12aa45b44d236815d282b03cfb1de3b4323f3e4ec933acfae08e54ade"},
{file = "coverage-7.4.4-cp39-cp39-win32.whl", hash = "sha256:d89d7b2974cae412400e88f35d86af72208e1ede1a541954af5d944a8ba46c57"},
{file = "coverage-7.4.4-cp39-cp39-win_amd64.whl", hash = "sha256:9ca28a302acb19b6af89e90f33ee3e1906961f94b54ea37de6737b7ca9d8827c"},
{file = "coverage-7.4.4-pp38.pp39.pp310-none-any.whl", hash = "sha256:b2c5edc4ac10a7ef6605a966c58929ec6c1bd0917fb8c15cb3363f65aa40e677"},
{file = "coverage-7.4.4.tar.gz", hash = "sha256:c901df83d097649e257e803be22592aedfd5182f07b3cc87d640bbb9afd50f49"},
]
[package.extras]
toml = ["tomli"]
[[package]]
name = "dictor"
version = "0.1.12"
description = "an elegant dictionary and JSON handler"
optional = false
python-versions = "*"
files = [
{file = "dictor-0.1.12.tar.gz", hash = "sha256:6db48375ae1e53dc9ed844e85b38f4e3fbfbf6a4e60beca377515ad14453b91b"},
]
[[package]]
name = "iniconfig"
version = "2.0.0"
description = "brain-dead simple config-ini parsing"
optional = false
python-versions = ">=3.7"
files = [
{file = "iniconfig-2.0.0-py3-none-any.whl", hash = "sha256:b6a85871a79d2e3b22d2d1b94ac2824226a63c6b741c88f7ae975f18b6778374"},
{file = "iniconfig-2.0.0.tar.gz", hash = "sha256:2d91e135bf72d31a410b17c16da610a82cb55f6b0477d1a902134b24a455b8b3"},
]
[[package]]
name = "mypy-extensions"
version = "1.0.0"
description = "Type system extensions for programs checked with the mypy type checker."
optional = false
python-versions = ">=3.5"
files = [
{file = "mypy_extensions-1.0.0-py3-none-any.whl", hash = "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d"},
{file = "mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782"},
]
[[package]]
name = "packaging"
version = "24.0"
description = "Core utilities for Python packages"
optional = false
python-versions = ">=3.7"
files = [
{file = "packaging-24.0-py3-none-any.whl", hash = "sha256:2ddfb553fdf02fb784c234c7ba6ccc288296ceabec964ad2eae3777778130bc5"},
{file = "packaging-24.0.tar.gz", hash = "sha256:eb82c5e3e56209074766e6885bb04b8c38a0c015d0a30036ebe7ece34c9989e9"},
]
[[package]]
name = "pathspec"
version = "0.12.1"
description = "Utility library for gitignore style pattern matching of file paths."
optional = false
python-versions = ">=3.8"
files = [
{file = "pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08"},
{file = "pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712"},
]
[[package]]
name = "platformdirs"
version = "4.2.0"
description = "A small Python package for determining appropriate platform-specific dirs, e.g. a \"user data dir\"."
optional = false
python-versions = ">=3.8"
files = [
{file = "platformdirs-4.2.0-py3-none-any.whl", hash = "sha256:0614df2a2f37e1a662acbd8e2b25b92ccf8632929bc6d43467e17fe89c75e068"},
{file = "platformdirs-4.2.0.tar.gz", hash = "sha256:ef0cc731df711022c174543cb70a9b5bd22e5a9337c8624ef2c2ceb8ddad8768"},
]
[package.extras]
docs = ["furo (>=2023.9.10)", "proselint (>=0.13)", "sphinx (>=7.2.6)", "sphinx-autodoc-typehints (>=1.25.2)"]
test = ["appdirs (==1.4.4)", "covdefaults (>=2.3)", "pytest (>=7.4.3)", "pytest-cov (>=4.1)", "pytest-mock (>=3.12)"]
[[package]]
name = "pluggy"
version = "1.4.0"
description = "plugin and hook calling mechanisms for python"
optional = false
python-versions = ">=3.8"
files = [
{file = "pluggy-1.4.0-py3-none-any.whl", hash = "sha256:7db9f7b503d67d1c5b95f59773ebb58a8c1c288129a88665838012cfb07b8981"},
{file = "pluggy-1.4.0.tar.gz", hash = "sha256:8c85c2876142a764e5b7548e7d9a0e0ddb46f5185161049a79b7e974454223be"},
]
[package.extras]
dev = ["pre-commit", "tox"]
testing = ["pytest", "pytest-benchmark"]
[[package]]
name = "pytest"
version = "8.1.1"
description = "pytest: simple powerful testing with Python"
optional = false
python-versions = ">=3.8"
files = [
{file = "pytest-8.1.1-py3-none-any.whl", hash = "sha256:2a8386cfc11fa9d2c50ee7b2a57e7d898ef90470a7a34c4b949ff59662bb78b7"},
{file = "pytest-8.1.1.tar.gz", hash = "sha256:ac978141a75948948817d360297b7aae0fcb9d6ff6bc9ec6d514b85d5a65c044"},
]
[package.dependencies]
colorama = {version = "*", markers = "sys_platform == \"win32\""}
iniconfig = "*"
packaging = "*"
pluggy = ">=1.4,<2.0"
[package.extras]
testing = ["argcomplete", "attrs (>=19.2)", "hypothesis (>=3.56)", "mock", "pygments (>=2.7.2)", "requests", "setuptools", "xmlschema"]
[[package]]
name = "pytest-cov"
version = "5.0.0"
description = "Pytest plugin for measuring coverage."
optional = false
python-versions = ">=3.8"
files = [
{file = "pytest-cov-5.0.0.tar.gz", hash = "sha256:5837b58e9f6ebd335b0f8060eecce69b662415b16dc503883a02f45dfeb14857"},
{file = "pytest_cov-5.0.0-py3-none-any.whl", hash = "sha256:4f0764a1219df53214206bf1feea4633c3b558a2925c8b59f144f682861ce652"},
]
[package.dependencies]
coverage = {version = ">=5.2.1", extras = ["toml"]}
pytest = ">=4.6"
[package.extras]
testing = ["fields", "hunter", "process-tests", "pytest-xdist", "virtualenv"]
[metadata]
lock-version = "2.0"
python-versions = "^3.11"
content-hash = "d16831490935fcd7e22800200d45343dd11ea57d9e76e1f77e8eb567d8aab89b"
[tool.poetry]
name = "dict-mapper"
version = "1.0.0"
description = "dict to dict mapping, allow transform the original structure given a specification"
authors = ["Miguel Galindo Rodriguez <mgalindo@palo-it.com>"]
readme = "README.md"
packages = [{include = "dict_mapper", from = "src"}]
[tool.poetry.dependencies]
python = "^3.11"
dictor = "^0.1.12"
[tool.poetry.group.dev.dependencies]
pytest = "^8.1.1"
black = "^24.3.0"
pytest-cov = "^5.0.0"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
[tool.pytest.ini_options]
testpaths = "tests"
filterwarnings = ["error", "ignore:The 'app' shortcut is now deprecated"]
log_cli = false
log_cli_level = "INFO"
log_cli_format = "%(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)"
log_cli_date_format = "%Y-%m-%d %H:%M:%S"
[tool.coverage.run]
branch = true
source = ['src/dict_mapper']
[tool.coverage.report]
skip_empty = true
exclude_also = ["def __repr__", "raise AssertionError", "raise NotImplementedError", "@(abc\\.)?abstractmethod", "pass"]
import copy
import logging
from datetime import datetime, date
from typing import Any, Type
from dictor import dictor
logger = logging.getLogger(__name__)
TRUE_STRINGS = ("yes", "true", "t", "1")
FALSE_STRINGS = ("no", "false", "f", "0")
skip = type("skip", (), {})
def constant(value):
return lambda _: value
def or_default(key, default):
return lambda d: dictor(d, key, default=default)
def calculate_from_original(func):
return lambda d: func(d)
def calculate_from_key(key, transform, default=None):
return lambda d: transform(dictor(d, key, default=default))
def factory(func):
return lambda _: func()
def datetime_now():
return lambda _: datetime.now()
def date_today():
return lambda _: date.today()
def convert_bool(value: str):
value_lower = value.lower()
if value_lower in TRUE_STRINGS:
return True
elif value_lower in FALSE_STRINGS:
return False
return None
def convert_date(value: str, _format: str) -> date:
if _format is None:
return datetime.fromisoformat(value).date()
else:
return datetime.strptime(value, _format).date()
def convert_datetime(value: str, _format: str) -> datetime:
if _format is None:
return datetime.fromisoformat(value)
else:
return datetime.strptime(value, _format)
def with_type(key: str, rtype: Type[Any], default=None, _format: str = None):
conversion_map = {
bool: convert_bool,
date: lambda value: convert_date(value, _format),
datetime: lambda value: convert_datetime(value, _format),
}
def convert(data: dict) -> Any:
value = dictor(data, key)
if value is None:
return default
elif rtype in conversion_map:
convert_func = conversion_map[rtype]
return convert_func(value)
else:
return rtype(value)
return convert
def __set_nested(obj: dict, path: str, value) -> None:
if "." in path:
*path, last = path.split(".")
for bit in path:
if bit not in obj:
obj[bit] = {}
obj = obj[bit]
obj[last] = value
else:
obj[path] = value
def __remove_nested(obj: dict, path: str) -> None:
if "." in path:
*path, last = path.split(".")
key_exist = True
for bit in path:
if bit not in obj:
key_exist = False
break
obj = obj[bit]
if key_exist:
obj.pop(last, None)
else:
logger.warning("Key not found: %s", path)
else:
obj.pop(path, None)
def map_dict(
original_dict: dict,
specification: dict,
keep_unmapped: bool = False,
) -> dict:
"""
Transforms an input dictionary according to a given specification.
Args:
original_dict (dict): The original dictionary to be transformed.
specification (dict): A dictionary specifying how the original dictionary should be transformed.
The keys are the keys of the new dictionary and the values can be:
- A string representing the key in the original dictionary.
- An instance of the 'skip' class to indicate that the key should be omitted.
- A function that takes the original dictionary and returns a value. Eg lambda original_dict: original_dict["key"] + "suffix"
The following functions are available for use in the specification:
- `constant(value)`: Assigns the given value to the given specification key.
- `or_default(key, default)`: Assigns the value of the key in the dictionary or the default value if the key is not present.
- `calculate_from_original(func)`: Applies the given function to the original dictionary and assigns the result to the given key.
- `calculate_from_key(key, transform, default=None)`: Applies the transform function to the value of the key in the dictionary and assigns the result to the given key.
- `factory(func)`: Applies the function with no arguments and assigns the result to the given key. Useful for generating unique IDs or initialize objects such as list or dict.
- `datetime_now()`: Assigns the current datetime in the given key.
- `date_today()`: Assigns the current date in the given key.
- `with_type(key: str, rtype: Type[Any], default=None, _format: str = None)`: Applies a str to bool,date,datetime convertion to the value of the key in the dictionary to the given type.
keep_unmapped (bool, optional): If True, the original dictionary will be kept in the new dictionary.
Defaults to False, which means only keys in specification will be present in the result.
Returns:
dict: A new dictionary that has been transformed according to the given specification.
"""
new_dict = {}
if keep_unmapped:
new_dict = copy.deepcopy(original_dict)
for key_target, key_origin in specification.items():
if isinstance(key_origin, str):
value = dictor(original_dict, key_origin)
__set_nested(new_dict, key_target, copy.deepcopy(value))
elif isinstance(key_origin, skip):
__remove_nested(new_dict, key_target)
elif callable(key_origin):
__set_nested(new_dict, key_target, key_origin(original_dict))
else:
logger.warning(
"Unexpected type for mapping key_origin:[%s], type:[%s]",
repr(key_origin),
type(key_origin),
)
return new_dict
import logging
import uuid
from datetime import date, datetime
import pytest
from dict_mapper.mapping import (
calculate_from_key,
calculate_from_original,
constant,
date_today,
datetime_now,
factory,
map_dict,
or_default,
with_type,
skip,
)
logger = logging.getLogger(__name__)
def get_id():
return "ID"
def calculate_complete_name(original_dict):
return original_dict["data"]["firstName"] + " " + original_dict["data"]["lastName"]
def generate_status(original_status):
if original_status is not None:
return original_status.upper()
else:
return "UNDEFINED"
def get_email(emailAddresses):
email = None
for emailAddress in emailAddresses:
if emailAddress["isPrimary"]:
email = emailAddress["email"]
break
return email
@pytest.fixture
def person_response():
return {
"data": {
"id": "f4fe41a5-5da4-480d-8f83-856b8cf5a138",
"displayName": "Abiran Natanael Salas Hernandez",
"firstName": "Abiran Natanael",
"lastName": "Salas Hernandez",
"dateOfBirth": "1991-10-07",
"gender": "Hombre",
"isSupervisor": False,
"isMarried": "false",
"employeeNumber": "096-MEX",
"employmentStatus": "Current Staff",
"addresses": [
{
"addressType": "Casa",
"fullAddress": "Manuel Fernando de Soto 127, Constitución de la República, Mexico City, CDMX",
"country": "Mexico",
"postcode": "07469",
"state": "Ciudad de México",
"street": "127 Manuel Fernando de Soto",
"suburb": "Ciudad de México",
"isPrimary": True,
"customFields": {},
"emailAddresses": [
{
"email": "asalas@palo-it.com",
"isPrimary": True,
"isPersonal": False,
"customFields": {},
},
{
"email": "abisaher@gmail.com",
"isPrimary": False,
"isPersonal": True,
"customFields": {},
},
],
}
],
"first_commit": "2022-11-11T22:38:14+00:00",
}
}
def test_map(person_response):
# given:
specification = {
"id": factory(get_id),
"name": "data.displayName",
"dob": with_type("data.dateOfBirth", rtype=date),
"gender_str": or_default(key="not_exist", default="Male"),
"is_supervisor": or_default(key="data.isSupervisor", default=True),
"complete_name": calculate_from_original(calculate_complete_name),
"employment_status": calculate_from_key(
key="data.employmentStatus",
default="Developer",
transform=generate_status,
),
"employment": calculate_from_key(
key="employment", default="Developer", transform=generate_status
),
"dojo": calculate_from_key(key="dojo", transform=generate_status),
"status": constant("ACTIVE"),
"first_commit": with_type("data.first_commit", rtype=datetime),
"created_at": datetime_now(),
"today": date_today(),
"isMarried": with_type(key="data.isMarried", rtype=bool),
"isHaveKids": with_type(key="data.not_exist", rtype=bool, default=False),
"isTodayBirthday": with_type(key="data.dateOfBirth", rtype=bool),
"not_exist": "not_exist",
}
# when:
result = map_dict(person_response, specification)
# then:
assert result is not None
assert result["id"] == "ID"
assert result["name"] == "Abiran Natanael Salas Hernandez"
assert result["dob"] == datetime.strptime("1991-10-07", "%Y-%m-%d").date()
assert result["gender_str"] == "Male"
assert result["is_supervisor"] == False
assert result["complete_name"] == "Abiran Natanael Salas Hernandez"
assert result["employment_status"] == "CURRENT STAFF"
assert result["employment"] == "DEVELOPER"
assert result["dojo"] == "UNDEFINED"
assert result["status"] == "ACTIVE"
assert result["first_commit"] == datetime.fromisoformat("2022-11-11T22:38:14+00:00")
assert result["created_at"].date() == datetime.today().date()
assert result["today"] == datetime.today().date()
assert result["isMarried"] is False
assert result["isHaveKids"] is False
assert result["isTodayBirthday"] is None
assert result["not_exist"] is None
def test_map_no_correct_key_type():
original = {"first_name": "Mac"}
specification = {"first_name": 5}
result = map_dict(original, specification)
assert len(result) == 0
def test_map_with_keep_unmapped():
original = {"first_name": "Mac", "last_name": "Doe", "age": 30, "dob": "1990-01-01"}
specification = {
"id": factory(lambda: str(uuid.uuid4())),
"first_name": skip(),
"last_name": skip(),
"full_name": calculate_from_original(
lambda d: d["first_name"] + " " + d["last_name"]
),
}
result = map_dict(original, specification, keep_unmapped=True)
print(result)
"""
{
"age": 30,
"dob": "1990-01-01",
"id": "160281d4-a243-46b1-b3ac-23e7de7eb178",
"full_name": "Mac Doe",
}
"""
assert result["first_name"] == "Mac"
assert result["last_name"] == "Doe"
assert result["age"] == 30
assert result["dob"] == "1990-01-01"
assert result["full_name"] == "Mac Doe"
def test_map_with_keep_unmapped_with_skip():
original = {
"first_name": "Mac",
"last_name": "Doe",
"age": 30,
"dob": "1990-01-01",
"address": {
"street": "127 Manuel Fernando de Soto",
"suburb": "Ciudad de México",
"postcode": "07469",
},
}
specification = {
"first_name": skip(),
"last_name": skip(),
"home_address": "address",
"home_address.suburb": skip(),
"home_address.country.code": skip(),
"full_name": calculate_from_original(
lambda d: d["first_name"] + " " + d["last_name"]
),
}
result = map_dict(original, specification, keep_unmapped=True)
assert result.get("first_name") is None
assert result.get("last_name") is None
assert result["age"] == 30
assert result["dob"] == "1990-01-01"
assert result["full_name"] == "Mac Doe"
assert result["full_name"] == "Mac Doe"
assert result["home_address"] is not None
assert result["home_address"]["postcode"] == "07469"
assert result["home_address"]["street"] == "127 Manuel Fernando de Soto"
assert "suburb" not in result["home_address"]
def test_map_with_nested_specs():
original = {"first_name": "Mac", "last_name": "Doe", "age": 30, "dob": "1990-01-01"}
specification = {"name.first_name": "first_name", "name.last_name": "last_name"}
result = map_dict(original, specification)
assert result["name"]["first_name"] == "Mac"
assert result["name"]["last_name"] == "Doe"
assert "age" not in result
assert "dob" not in result
def test_with_type_no_correct_type():
# Preparación de datos y función
error_converter = with_type(key="dob", rtype=date)
data = {"dob": "hello"}
# Ejecución y verificación
with pytest.raises(Exception):
error_converter(data)
@pytest.mark.parametrize(
"val,expected",
[
("true", True),
("True", True),
("t", True),
("1", True),
("yes", True),
("false", False),
("False", False),
("f", False),
("0", False),
("no", False),
],
)
def test_with_type_bool(val, expected):
# Preparación de datos y función
bool_converter = with_type(key="isSupervisor", rtype=bool)
data = {"isSupervisor": val}
# Ejecución y verificación
assert bool_converter(data) is expected
def test_with_type_int():
int_converter = with_type(key="age", rtype=int)
data = {"age": "30"}
assert int_converter(data) == 30
def test_with_type_float():
float_converter = with_type(key="rating", rtype=float)
data = {"rating": "4.5"}
assert float_converter(data) == 4.5
def test_with_type_date():
date_converter = with_type(key="dob", rtype=date, _format="%Y-%m-%d")
data = {"dob": "1990-01-01"}
assert date_converter(data) == date(1990, 1, 1)
def test_with_type_datetime():
datetime_converter = with_type(
key="last_update", rtype=datetime, _format="%Y-%m-%dT%H:%M:%S.%fZ"
)
data = {"last_update": "2020-05-20T15:30:00.000Z"}
assert datetime_converter(data) == datetime(2020, 5, 20, 15, 30)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment