Skip to main content

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:

pip install enum-with-dict

Usage

Defining an Enum with EnumWithDict

from enum_with_dict import EnumWithDict

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

Converting an Enum to a Dictionary

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

Getting the Initial Enum Value

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

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

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

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

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

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.

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.

# 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.

# 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

keys_list = Color.keys()

Get keys as a KeysView

keys_view = Color.keys(as_list=False)

Get values as a list

values_list = Color.values()

Get values as a ValuesView

values_view = Color.values(as_list=False)

LICENSE

EnumWithDict is released under the MIT License. See the LICENSE file for more details.

Metadata

Release files for enum-with-dict 0.7.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for enum-with-dict 0.7.2
File Size Uploaded Provenance Actions
enum_with_dict-0.7.2.tar.gz 6.8 kB Without provenance Details for enum_with_dict-0.7.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for enum-with-dict 0.7.2
File Interpreter ABI Platform Actions
enum_with_dict-0.7.2-py3-none-any.whl Python 3 none any Details for enum_with_dict-0.7.2-py3-none-any.whl

Total release size: 14.6 kB

Release files / enum_with_dict-0.7.2.tar.gz

Download URL enum_with_dict-0.7.2.tar.gz
Size 6.8 kB
Tags Source
SHA-256 checksum
How to use checksums
cf13b715a3b2a2cac4495009a39dde9ec7e3be6a2d198a49fb0661cb66307dad
BLAKE2b-256 checksum
How to use checksums
af4bc1900597a42cf9469828623a6ab7b5815188177b2909ea440b8c856cba3a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.0.0 CPython/3.11.6

Release files / enum_with_dict-0.7.2-py3-none-any.whl

Download URL enum_with_dict-0.7.2-py3-none-any.whl
Size 7.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e35201948740f0f3a489b63c3806c06c90a5788017f708919efc6af31e371ec7
BLAKE2b-256 checksum
How to use checksums
ee01a78d45e7d056c3f9394c0617da11034971d4719bc50ddeb69c32d15893ee
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.0.0 CPython/3.11.6

Security for enum-with-dict 0.7.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page