enum-with-dict


Nameenum-with-dict JSON
Version 0.7.1 PyPI version JSON
download
home_pagehttps://github.com/jzombie/py-enum-with-dict
SummaryEnum with to_dict method.
upload_time2024-04-04 11:07:35
maintainerNone
docs_urlNone
authorJeremy Harris
requires_python>=3.7
licenseMIT
keywords enum python utilities enum-to-dict enum-with-dict
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # EnumWithDict

`EnumWithDict` is a Python package that extends the standard library's Enum class to include `to_dict`, `get_initial`, and other class methods. This enhancement allows for the straightforward conversion of enum classes to dictionaries, easy access to the initial enum value, and additional functionalities such as retrieving enum values with a fallback option, validating mappings, and more.

## Extends Enum with the Following Methods:

- **to_dict**: Convert an enum class to a dictionary representation, mapping member names to their values.
- **get_initial**: Retrieve the first value defined in the enum, useful for cases where a default or initial value is needed.
- **get**: Mimics the dictionary `get` method, allowing retrieval of enum values with an optional default fallback. Additionally, it supports an optional custom mapping dictionary for dynamically mapped value retrieval.
- **validate_mapping_keys**: Ensure that a provided mapping includes all enum values, raising an error for any missing mappings.
- **map**: Map enum members to values based on the provided dictionary.
- **keys**: Retrieve the keys of the enum class as a list or as a KeysView.
- **values**: Retrieve the values of the enum class as a list or as a ValuesView.

## Installation

Install `EnumWithDict` using pip:

```bash
pip install enum-with-dict
```

## Usage

### Defining an Enum with `EnumWithDict`

```python
from enum_with_dict import EnumWithDict

class Color(EnumWithDict):
    RED = 'red'
    GREEN = 'green'
    BLUE = 'blue'

```

### Converting an Enum to a Dictionary

```python
color_dict = Color.to_dict()
print(color_dict)
# Output: {'RED': 'red', 'GREEN': 'green', 'BLUE': 'blue'}
```

### Getting the Initial Enum Value

```python
initial_color = Color.get_initial()
print(initial_color)
# Output: 'red'
```

### Using the `get` Method

Retrieve an enum value by its name, with an option to specify a default value if the name does not exist. Additionally, you can pass a custom mapping dictionary to retrieve a mapped value instead of the enum's default value.

#### Get a value for an existing key

```python
print(Color.get('RED'))  # Output: 'red'
```

### Get a value for a non-existing key with a default value

```python
print(Color.get('PURPLE', default='unknown'))  # Output: 'unknown'
```

### Get a value for a non-existing key, falling back to the initial value

```python
print(Color.get('PURPLE'))  # Output: 'red'
```

### Get a value using a custom mapping

You can also use a custom mapping dictionary to retrieve a value. This is useful when you need to map enum members to different values dynamically.

```python
custom_mapping = {'RED': 'Rouge', 'GREEN': 'Vert', 'BLUE': 'Bleu'}
print(Color.get('RED', mapping=custom_mapping))  # Output: 'Rouge'
```

## Ensuring Completeness of Mappings with `validate_mapping_keys`

Validate that a provided mapping covers all enum members.

```python
# Assuming a partial mapping for demonstration
partial_mapping = {'RED': 'Rouge', 'GREEN': 'Vert'}

try:
    Color.validate_mapping_keys(partial_mapping)
except ValueError as e:
    print(e)
# Expected output: Missing mappings for: BLUE
```

### Mapping Enum Members with `map`

Map enum members to values using the provided dictionary.

This mapping operation does not alter the values within the Enum itself; instead, it generates a new dictionary with the same keys and updated values.

Internally, `validate_mapping_keys` is invoked to confirm that the keys align with the Enum members, but the value types remain arbitrary.

```python
# Define the key mapping
key_mapping = {
    TestEnum.VALUE_1: "some_new_value",
    TestEnum.VALUE_2: "another_new_value",
    TestEnum.VALUE_3: "a new value"
}

# Perform the mapping and validate
mapped_values = TestEnum.map(key_mapping)

# ----- The above is equivalent to the following: -----

# Validate the mapped values
expected_values = {
    TestEnum.VALUE_1.name: "some_new_value",
    TestEnum.VALUE_2.name: "another_new_value",
    TestEnum.VALUE_3.name: "a new value"
}

assert mapped_values == expected_values

```

## Retrieving Keys and Values with `keys()` and `values()`

Retrieve the keys and values of the enum class as a list or as a `KeysView` or `ValuesView`.

### Get keys as a list

```python
keys_list = Color.keys()
```

### Get keys as a `KeysView`

```python
keys_view = Color.keys(as_list=False)
```

### Get values as a list

```python
values_list = Color.values()
```

### Get values as a ValuesView

```python
values_view = Color.values(as_list=False)
```

## LICENSE

`EnumWithDict` is released under the MIT License. See the [LICENSE](LICENSE) file for more details.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/jzombie/py-enum-with-dict",
    "name": "enum-with-dict",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": "enum python utilities enum-to-dict enum-with-dict",
    "author": "Jeremy Harris",
    "author_email": "jeremy.harris@zenosmosis.com",
    "download_url": "https://files.pythonhosted.org/packages/89/b3/f7d3687996a04726f7bb9d4ecc37725a9e534d5021470ea0e8f4007dc92b/enum_with_dict-0.7.1.tar.gz",
    "platform": null,
    "description": "# EnumWithDict\n\n`EnumWithDict` is a Python package that extends the standard library's Enum class to include `to_dict`, `get_initial`, and other class methods. This enhancement allows for the straightforward conversion of enum classes to dictionaries, easy access to the initial enum value, and additional functionalities such as retrieving enum values with a fallback option, validating mappings, and more.\n\n## Extends Enum with the Following Methods:\n\n- **to_dict**: Convert an enum class to a dictionary representation, mapping member names to their values.\n- **get_initial**: Retrieve the first value defined in the enum, useful for cases where a default or initial value is needed.\n- **get**: Mimics the dictionary `get` method, allowing retrieval of enum values with an optional default fallback. Additionally, it supports an optional custom mapping dictionary for dynamically mapped value retrieval.\n- **validate_mapping_keys**: Ensure that a provided mapping includes all enum values, raising an error for any missing mappings.\n- **map**: Map enum members to values based on the provided dictionary.\n- **keys**: Retrieve the keys of the enum class as a list or as a KeysView.\n- **values**: Retrieve the values of the enum class as a list or as a ValuesView.\n\n## Installation\n\nInstall `EnumWithDict` using pip:\n\n```bash\npip install enum-with-dict\n```\n\n## Usage\n\n### Defining an Enum with `EnumWithDict`\n\n```python\nfrom enum_with_dict import EnumWithDict\n\nclass Color(EnumWithDict):\n    RED = 'red'\n    GREEN = 'green'\n    BLUE = 'blue'\n\n```\n\n### Converting an Enum to a Dictionary\n\n```python\ncolor_dict = Color.to_dict()\nprint(color_dict)\n# Output: {'RED': 'red', 'GREEN': 'green', 'BLUE': 'blue'}\n```\n\n### Getting the Initial Enum Value\n\n```python\ninitial_color = Color.get_initial()\nprint(initial_color)\n# Output: 'red'\n```\n\n### Using the `get` Method\n\nRetrieve an enum value by its name, with an option to specify a default value if the name does not exist. Additionally, you can pass a custom mapping dictionary to retrieve a mapped value instead of the enum's default value.\n\n#### Get a value for an existing key\n\n```python\nprint(Color.get('RED'))  # Output: 'red'\n```\n\n### Get a value for a non-existing key with a default value\n\n```python\nprint(Color.get('PURPLE', default='unknown'))  # Output: 'unknown'\n```\n\n### Get a value for a non-existing key, falling back to the initial value\n\n```python\nprint(Color.get('PURPLE'))  # Output: 'red'\n```\n\n### Get a value using a custom mapping\n\nYou can also use a custom mapping dictionary to retrieve a value. This is useful when you need to map enum members to different values dynamically.\n\n```python\ncustom_mapping = {'RED': 'Rouge', 'GREEN': 'Vert', 'BLUE': 'Bleu'}\nprint(Color.get('RED', mapping=custom_mapping))  # Output: 'Rouge'\n```\n\n## Ensuring Completeness of Mappings with `validate_mapping_keys`\n\nValidate that a provided mapping covers all enum members.\n\n```python\n# Assuming a partial mapping for demonstration\npartial_mapping = {'RED': 'Rouge', 'GREEN': 'Vert'}\n\ntry:\n    Color.validate_mapping_keys(partial_mapping)\nexcept ValueError as e:\n    print(e)\n# Expected output: Missing mappings for: BLUE\n```\n\n### Mapping Enum Members with `map`\n\nMap enum members to values using the provided dictionary.\n\nThis mapping operation does not alter the values within the Enum itself; instead, it generates a new dictionary with the same keys and updated values.\n\nInternally, `validate_mapping_keys` is invoked to confirm that the keys align with the Enum members, but the value types remain arbitrary.\n\n```python\n# Define the key mapping\nkey_mapping = {\n    TestEnum.VALUE_1: \"some_new_value\",\n    TestEnum.VALUE_2: \"another_new_value\",\n    TestEnum.VALUE_3: \"a new value\"\n}\n\n# Perform the mapping and validate\nmapped_values = TestEnum.map(key_mapping)\n\n# ----- The above is equivalent to the following: -----\n\n# Validate the mapped values\nexpected_values = {\n    TestEnum.VALUE_1.name: \"some_new_value\",\n    TestEnum.VALUE_2.name: \"another_new_value\",\n    TestEnum.VALUE_3.name: \"a new value\"\n}\n\nassert mapped_values == expected_values\n\n```\n\n## Retrieving Keys and Values with `keys()` and `values()`\n\nRetrieve the keys and values of the enum class as a list or as a `KeysView` or `ValuesView`.\n\n### Get keys as a list\n\n```python\nkeys_list = Color.keys()\n```\n\n### Get keys as a `KeysView`\n\n```python\nkeys_view = Color.keys(as_list=False)\n```\n\n### Get values as a list\n\n```python\nvalues_list = Color.values()\n```\n\n### Get values as a ValuesView\n\n```python\nvalues_view = Color.values(as_list=False)\n```\n\n## LICENSE\n\n`EnumWithDict` is released under the MIT License. See the [LICENSE](LICENSE) file for more details.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Enum with to_dict method.",
    "version": "0.7.1",
    "project_urls": {
        "Homepage": "https://github.com/jzombie/py-enum-with-dict"
    },
    "split_keywords": [
        "enum",
        "python",
        "utilities",
        "enum-to-dict",
        "enum-with-dict"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "236639f0d93e669e1f2ded94d63471f585df99493a5ba93f10eb8db70aa51ea1",
                "md5": "26b410082e32d78063b1f73b54f0d6fa",
                "sha256": "013faf56f61e57d1efb707581bb4f61fef1d83f9600f296a840ebbbf209f5e57"
            },
            "downloads": -1,
            "filename": "enum_with_dict-0.7.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "26b410082e32d78063b1f73b54f0d6fa",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 7795,
            "upload_time": "2024-04-04T11:07:34",
            "upload_time_iso_8601": "2024-04-04T11:07:34.306680Z",
            "url": "https://files.pythonhosted.org/packages/23/66/39f0d93e669e1f2ded94d63471f585df99493a5ba93f10eb8db70aa51ea1/enum_with_dict-0.7.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "89b3f7d3687996a04726f7bb9d4ecc37725a9e534d5021470ea0e8f4007dc92b",
                "md5": "df71605088de872aecb7651b0e05ecc1",
                "sha256": "8dfa5815eb667548a5c041c1c53506c96223d984441b839db4334c526fef201b"
            },
            "downloads": -1,
            "filename": "enum_with_dict-0.7.1.tar.gz",
            "has_sig": false,
            "md5_digest": "df71605088de872aecb7651b0e05ecc1",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 6821,
            "upload_time": "2024-04-04T11:07:35",
            "upload_time_iso_8601": "2024-04-04T11:07:35.708885Z",
            "url": "https://files.pythonhosted.org/packages/89/b3/f7d3687996a04726f7bb9d4ecc37725a9e534d5021470ea0e8f4007dc92b/enum_with_dict-0.7.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-04 11:07:35",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "jzombie",
    "github_project": "py-enum-with-dict",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "enum-with-dict"
}
        
Elapsed time: 0.22111s