Skip to content

Is there an easier way to pre-process incoming values for specific fields? #797

Open
@amogus07

Description

Question

I want to convert an incoming comma-separated string to a set of enum members.
This is my current solution:

# to avoid extra whitespace
SPLIT_PATTERN: re.Pattern[str] = re.compile(r"\s*,\s*")


class AlbumArtist(TaggedBase, kw_only=True):
    _categories: str = msgspec.field(name="categories")
    _effective_roles: str = msgspec.field(name="effectiveRoles")
    is_support: bool
    name: str
    roles: str
    artist: Optional[Artist] = None
    categories: set[ArtistCategories] = msgspec.field(
        default_factory=set, name="dummy1"
    )
    effective_roles: set[ArtistRoles] = msgspec.field(
        default_factory=set, name="dummy2"
    )

    def __post_init__(self) -> None:
        self.categories = {
            ArtistCategories(c) for c in SPLIT_PATTERN.split(self._categories) if c
        }
        self.effective_roles = {
            ArtistRoles(r) for r in SPLIT_PATTERN.split(self._effective_roles) if r
        }

it's a snippet from https://github.com/prTopi/beets-vocadb/blob/2a2b3cca83449b26717ffff2a7bb085b26381d26/beetsplug/vocadb/requests_handler/models.py

Is there a more efficient way that doesn't involve additional attributes?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions