Skip to main content

Library provides fallback enum functionality. Fully compatible with pydantic.

Project description

FBEnum

Library provides fallback enum functionality. Fully compatible with pydantic.

It can be helpful to have a fallback value for enums, so that unknown values can be handled gracefully. This is especially useful when working with external data sources that may contain values that are not known at the time of writing the code.

Installation

pip install fbenum

Usage

fbenum provides two possible ways to use it:

  • As a class mixin, which can be used to enhance any enum class
  • As a pydantic validator, which can be used to validate enum values in pydantic models

Class mixin

Class mixin can be used to enhance any enum class with fallback functionality.

from enum import Enum
from fbenum.enum import FallbackEnum

@enum.unique
class MyEnum(enum.StrInt, FallbackEnum):
    __unknown_name__ = 'MISSING'

    A = 1
    B = 2

assert MyEnum(1) == MyEnum.A
assert MyEnum(44).name == 'MISSING'
assert MyEnum(44).value == 44

Pydantic validator

As a pydantic validator, fbenum can be used to validate enum values in pydantic models. In this cases, the enum class no longer needs to be a subclass of FallbackEnum or somehow otherwise enhanced. Two ways of using it are provided:

Annotated type validator

from enum import Enum
from fbenum.adapter import FallbackAdapter

@enum.unique
class MyEnum(enum.StrInt):
    A = 1
    B = 2

class MyModel(BaseModel):
    value: Annotated[
        MyEnum, FallbackAdapter(unknown_name='MISSING'),
    ]

model = MyModel(value=1)
assert model.value == MyEnum.A

model = MyModel(value=44)
assert model.value.name == 'MISSING'
assert model.value.value == 44

Type wrapper

Type wrapper has restricted functionality, as it can only be used to wrap a single enum class, and it does not support any additional arguments. However, it is more concise.

from enum import Enum
from fbenum.adapter import FallbackAdapter

@enum.unique
class MyEnum(enum.StrInt):
    A = 1
    B = 2

class MyModel(BaseModel):
    value: FallbackAdapter[MyEnum]

model = MyModel(value=1)
assert model.value == MyEnum.A

model = MyModel(value=44)
assert model.value.name == 'MISSING'
assert model.value.value == 44
Or a more realistic and complex example:
from enum import Enum
from fbenum.adapter import FallbackAdapter


@enum.unique
class UserStatus(enum.StrInt):
    """User status."""
    ACTIVE = 1
    INACTIVE = 2


class UserRequest(BaseModel):
    name: str
    email: str
    status: FallbackAdapter[UserStatus]


class UserResponse(BaseModel):
    name: str
    email: str
    status: FallbackAdapter[UserStatus]


def create_user(request: UserRequest) -> UserResponse:
    """Create a user."""
    # Do some stuff
    resp = ...
    return UserResponse.validate_model(resp)


def get_user(user_id: int) -> UserResponse:
    """Get a user."""
    # Do some stuff
    resp = ...
    return UserResponse.validate_model(resp)


def get_users() -> list[UserResponse]:
    """Get all users."""
    # Do some stuff
    resp = ...
    return UserResponse.validate_model(resp)


if __name__ == '__main__':
    user = create_user(
        UserRequest(
            name='John Doe',
            email='test@emaik.com',
            status=1,
        ),
    )
    # on user cretion status always will be known

    users = get_users()
    # user == [
    #     UserResponse(
    #         name='John Doe',
    #         email='test@emaik',
    #         status=1,
    #     ),
    #     UserResponse(
    #         name='Jane Doe',
    #         email='test2@emaik',
    #         status=3, # unknown status
    # ]
    # on users_getting status can be unknown, so using fallback wrapper for response
    # model will be a good idea to handle unknown values gracefully.

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

fbenum-1.0.1.tar.gz (10.2 kB view details)

Uploaded Source

Built Distribution

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

fbenum-1.0.1-py3-none-any.whl (7.0 kB view details)

Uploaded Python 3

File details

Details for the file fbenum-1.0.1.tar.gz.

File metadata

  • Download URL: fbenum-1.0.1.tar.gz
  • Upload date:
  • Size: 10.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: pdm/2.12.1 CPython/3.10.12

File hashes

Hashes for fbenum-1.0.1.tar.gz
Algorithm Hash digest
SHA256 d2f2606dbd31318ff078a2e3cbf1bcecff6ea215d3f8ed2f626c6207dc5103ba
MD5 cc2b2150d3596821a77561460af222ed
BLAKE2b-256 0220319b3fabc1e52c3c11f9a8d35355b1013bc6a8fcbfc3d6202161eae6cbe7

See more details on using hashes here.

File details

Details for the file fbenum-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: fbenum-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 7.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: pdm/2.12.1 CPython/3.10.12

File hashes

Hashes for fbenum-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 5399582bfca2c8eb84b0836bade371f7f3408cbf23af4ec398fdc25ca98da434
MD5 8166f8de628533ae0acd752be9c2172c
BLAKE2b-256 da821bc16f7eac0aa61ed6ba368f807ddcd2dedfa6600a30c86c86a274373ae1

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