Skip to content

Can roles be defined as enums instead of strings? #427

@jace

Description

@jace

Roles are currently defined as string-only. No other object type is accepted, and a role match is defined as a plain string match. However, roles are also scoped to a class, so an editor role on one class is not necessarily the same role on another class. The names are re-used for convenience, to identify their function, but usually are not transferable. Renaming a class-specific role is painful because it requires a careful find and replace, avoiding other uses of the same string.

Could roles be defined as an enum instead? Using StrEnum (Python 3.11+, or LowercaseStrEnum from the StrEnum lib, or a custom implementation) may make it a drop-in replacement:

from enum import StrEnum, auto

class CommonRoles(StrEnum):
    ALL = auto()
    AUTH = auto()
    ANON = auto()

class MyClassRoles(StrEnum):
    EDITOR = auto()

class MyModel(RoleMixin):
    __roles__ = {
        CommonRoles.ALL: {'read': {'attr'}},
        MyClassRoles.EDITOR: {'write': {'attr'}},
    }

With this approach, enums and strings can be used interchangeably (to the developer's peril), but using an enum exclusively will make refactoring vastly easier (with caveats such as InspectableSet-based uses, which still need manual find and replace).

Question: what happens when the same name from two different enums is used in the same class? Are they the same role (as when using only strings) or different? Should we raise a warning when this happens, assuming it's detectable?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions