Core Modules¶
This page provides auto-generated API documentation for the core Highlander Enum modules.
highlander.enums¶
The main module containing ExFlag
and OptionsFlag
classes.
highlander.enums
¶
Classes¶
ExFlag
¶
Bases: IntFlag
An IntFlag variation supporting mutually exclusive flags with configurable conflict resolution.
ExFlag extends Python's IntFlag to provide "Highlander" behavior - when mutually exclusive flags are combined, only one can remain active (there can be only one). The conflict resolution strategy determines which flag wins when conflicts occur.
Flags can define mutual exclusions by passing a list of conflicting flags during definition. When conflicting flags are combined using bitwise operations, the configured conflict resolution strategy determines the outcome.
Attributes:
Name | Type | Description |
---|---|---|
__exclusives__ |
defaultdict[int, int]
|
Class variable storing bitmasks for mutually exclusive flags. |
Examples:
Basic usage with RHS (default) conflict resolution: >>> class MyFlag(ExFlag): ... FLAG1 = 1 ... FLAG2 = 2 ... EXCLUSIVE = 4, [FLAG1, FLAG2] # Conflicts with FLAG1 and FLAG2 >>> result = MyFlag.FLAG1 | MyFlag.EXCLUSIVE >>> result == MyFlag.EXCLUSIVE # RHS wins True
Using different conflict resolution strategies: >>> class StrictFlag(ExFlag, conflict="strict"): ... A = 1 ... B = 2, [A] >>> StrictFlag.A | StrictFlag.B # Raises ValueError Traceback (most recent call last): ValueError: ...conflicts with...
Functions¶
__init_subenum__(classdict, **kwargs)
¶Initialize exclusives tracking for each subclass.
This method is called by the metaclass to ensure each ExFlag subclass gets its own exclusives dictionary, preventing contamination between different enum classes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
classdict
|
dict[str, Any]
|
Dictionary of class attributes being created. |
required |
**kwargs
|
Any
|
Additional keyword arguments (unused). |
{}
|
Note
This is required because init_subclass isn't called until after all enum members and new have been processed.
__new__(value, *args)
¶Create new ExFlag enum members with optional exclusion definitions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cls
|
type[ExFlag]
|
The ExFlag class being instantiated. |
required |
value
|
int
|
The integer value for this flag. |
required |
*args
|
Any
|
Optional arguments where the last argument can be a list of flags that should be mutually exclusive with this flag. |
()
|
Returns:
Type | Description |
---|---|
Self
|
A new ExFlag instance with the specified value and exclusions. |
Note
If exclusions are provided, they are automatically registered as mutually exclusive with this flag using add_mutual_exclusions.
__call__(value)
¶Create an ExFlag instance from an integer value, resolving conflicts.
This method is called when creating enum instances from integer values, such as MyFlag(5). It applies conflict resolution by examining each bit in the value and removing conflicting flags according to the exclusion masks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cls
|
type[ExFlag]
|
The ExFlag class. |
required |
value
|
int | Any
|
Integer value to convert to an ExFlag instance. |
required |
Returns:
Type | Description |
---|---|
Self
|
An ExFlag instance with conflicts resolved according to the |
Self
|
class's conflict resolution strategy. |
Note
For STRICT mode, _handle_conflict may raise a ValueError if conflicts are detected in the original value.
add_mutual_exclusions(mutually_exclusive_values)
classmethod
¶Set multiple flags as mutually exclusive with each other.
Creates bitmasks stored in the exclusives mapping for fast conflict resolution during bitwise operations. All flags in the sequence will be mutually exclusive with each other - only one from the group can be active at a time.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mutually_exclusive_values
|
Sequence[IntFlag | int]
|
Sequence of flag values (integers or IntFlag instances) that should be mutually exclusive with each other. |
required |
Example
class MyFlag(ExFlag): ... A = 1 ... B = 2 ... C = 4 MyFlag.add_mutual_exclusions([MyFlag.A, MyFlag.B, MyFlag.C]) result = MyFlag.A | MyFlag.B # B wins (RHS) result == MyFlag.B True
add_exclusions(*exclusive_values)
¶Add flags that are mutually exclusive with this flag instance.
This method allows runtime addition of exclusion relationships between this flag and other flags. It creates bidirectional exclusions - this flag will exclude the specified flags, and the specified flags will exclude this flag.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*exclusive_values
|
IntFlag | int
|
Variable number of flags (integers or IntFlag instances) that should be mutually exclusive with this flag. |
()
|
Example
class MyFlag(ExFlag): ... A = 1 ... B = 2 ... C = 4 flag_a = MyFlag.A flag_a.add_exclusions(MyFlag.B, MyFlag.C) result = MyFlag.A | MyFlag.B # B wins due to RHS resolution result == MyFlag.B True
__handle_conflict_rhs__(other)
¶Handle conflicts using RHS (right-hand side) resolution strategy.
In RHS mode, when conflicting flags are combined, the right-hand side (newer) value wins. This is the default conflict resolution strategy.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other
|
int
|
Integer value containing the new flag(s) being combined. |
required |
Returns:
Type | Description |
---|---|
int
|
Bitmask that removes conflicting bits, allowing the RHS value to win. |
Example
If flag A conflicts with flag B, then A | B results in B.
__handle_conflict_lhs__(other)
¶Handle conflicts using LHS (left-hand side) resolution strategy.
In LHS mode, when conflicting flags are combined, the left-hand side (existing) value wins and conflicting new values are discarded.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other
|
int
|
Integer value containing the new flag(s) being combined (ignored for conflict resolution, but may be used for validation). |
required |
Returns:
Type | Description |
---|---|
int
|
Bitmask that preserves the current (LHS) value and excludes conflicts. |
Example
If flag A conflicts with flag B, then A | B results in A.
__handle_conflict_strict__(other)
¶Handle conflicts using STRICT mode - raise ValueError on any conflicts.
In STRICT mode, any attempt to combine conflicting flags raises a ValueError with a detailed message describing all conflicts found.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other
|
int
|
Integer value containing the new flag(s) being combined. |
required |
Returns:
Type | Description |
---|---|
int
|
Always returns -1 if no conflicts are found (allowing the operation). |
Raises:
Type | Description |
---|---|
ValueError
|
If any conflicts are detected between the current flags and the new flags being combined. |
Example
If flag A conflicts with flag B, then A | B raises ValueError.
__or__(other)
¶Perform bitwise OR operation with conflict resolution.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other
|
int
|
Integer value to combine with this flag. |
required |
Returns:
Type | Description |
---|---|
Self
|
New ExFlag instance with the combined value after conflict resolution. |
__xor__(other)
¶Perform bitwise XOR operation with conflict resolution.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other
|
int
|
Integer value to XOR with this flag. |
required |
Returns:
Type | Description |
---|---|
Self
|
New ExFlag instance with the XOR result after conflict resolution. |
OptionsFlag
¶
Bases: ExFlag
An ExFlag subclass designed for command-line options with rich member definitions.
OptionsFlag extends ExFlag to support command-line option scenarios where flags need aliases, help text, and exclusion relationships. Each flag is defined with a tuple containing the value, optional aliases, help text, and optional exclusions.
The class automatically creates properties for accessing help text and aliases, making it suitable for building command-line parsers and help systems.
Attributes:
Name | Type | Description |
---|---|---|
help |
str
|
Property providing read-only access to the flag's help text. |
aliases |
list[str]
|
Property providing read-only access to the flag's aliases. |
Examples:
Basic usage with help text and aliases: >>> class MyOptions(OptionsFlag): ... VERBOSE = 1, ["v", "verbose"], "Enable verbose output" ... QUIET = 2, ["q", "quiet"], "Enable quiet mode", [VERBOSE] >>> opt = MyOptions.VERBOSE >>> opt.help 'Enable verbose output' >>> opt.aliases ['v', 'verbose']
Tuple format variations: - (help_str,) - Just help text - ([aliases], help_str) - Aliases and help text - ([aliases], help_str, [exclusions]) - Full specification - (help_str, [exclusions]) - Help and exclusions without aliases
Attributes¶
help
property
¶Get the help text for this flag.
Returns:
Type | Description |
---|---|
str
|
The help text string provided during flag definition, or empty |
str
|
string if no help text was provided. |
aliases
property
¶Get the list of aliases for this flag.
Returns:
Type | Description |
---|---|
list[str]
|
List of string aliases that can be used to reference this flag. |
list[str]
|
Returns empty list if no aliases were defined or if the enum |
list[str]
|
doesn't have a value-to-member mapping. |
Note
Aliases are automatically registered with the enum's internal value2member_map when the flag is created.
Functions¶
__init__(*args, **kwargs)
¶Initialize an OptionsFlag instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args
|
Any
|
Variable positional arguments passed to parent class. |
()
|
**kwargs
|
Any
|
Variable keyword arguments passed to parent class. |
{}
|
Note
This initializer primarily exists to satisfy type checkers by declaring the _help attribute that gets set during new.
__new__(value, *args)
¶Create new OptionsFlag members with help text, aliases, and exclusions.
Parses the arguments tuple to extract help text, optional aliases, and optional exclusion relationships. The tuple format is flexible to support various common patterns for defining command-line options.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cls
|
type[OptionsFlag]
|
The OptionsFlag class being instantiated. |
required |
value
|
int
|
Integer value for this flag. |
required |
*args
|
Any
|
Variable arguments in one of these formats: - (help_str,) - Just help text - ([aliases], help_str) - Aliases list and help text - ([aliases], help_str, [exclusions]) - Full specification - (help_str, [exclusions]) - Help text and exclusions |
()
|
Returns:
Type | Description |
---|---|
Self
|
New OptionsFlag instance with help text, aliases, and exclusions configured. |
Raises:
Type | Description |
---|---|
TypeError
|
If no help string is provided or too many arguments are given. |
Example
class MyOptions(OptionsFlag): ... VERBOSE = 1, ["v", "verbose"], "Enable verbose output" ... QUIET = 2, "Enable quiet mode", [VERBOSE]
highlander.type¶
The metaclass and type system supporting Highlander Enum functionality.
highlander.type
¶
Classes¶
ConflictResolution
¶
Bases: StrEnum
Enumeration defining conflict resolution strategies for mutually exclusive flags.
This enum defines how Highlander enums should handle conflicts when mutually exclusive flags are combined. Each strategy provides different behavior when incompatible flags are used together in bitwise operations.
Attributes:
Name | Type | Description |
---|---|---|
RHS |
Right-hand side wins. The new value replaces the old value in conflicts. |
|
LHS |
Left-hand side wins. The old value is preserved, new conflicting values are discarded. |
|
STRICT |
Strict mode raises ValueError on any conflicts. |
Examples:
RHS (Right-hand side wins) - default behavior: >>> from highlander import ExFlag >>> class F(ExFlag, conflict="rhs"): ... FLAG1 = 1 ... EX_FLAG1 = 2 ... EX_FLAG2 = 4, [EX_FLAG1] >>> value = F.EX_FLAG1 >>> value |= F.FLAG1 | F.EX_FLAG2 >>> value == F.FLAG1 | F.EX_FLAG2 True
LHS (Left-hand side wins): >>> class F(ExFlag, conflict="lhs"): ... FLAG1 = 1 ... EX_FLAG1 = 2 ... EX_FLAG2 = 4, [EX_FLAG1] >>> value = F.EX_FLAG1 >>> value |= F.FLAG1 | F.EX_FLAG2 >>> value == F.FLAG1 | F.EX_FLAG1 True
STRICT (Raises on conflicts): >>> class F(ExFlag, conflict="strict"): ... FLAG1 = 1 ... EX_FLAG1 = 2 ... EX_FLAG2 = 4, [EX_FLAG1] >>> value = F.EX_FLAG1 >>> value |= F.FLAG1 | F.EX_FLAG2 Traceback (most recent call last): ValueError: F.EX_FLAG1 and F.EX_FLAG2 can't be combined
EnumPlusType
¶
Bases: EnumType
Metaclass for creating Enum subclasses with support for advanced features.
Metaclass for creating Enum subclasses with support for advanced features such as: - Better subclassing by supporting super().new. - Modify subclasses through init_subenum. - Control member lookups by implementing call. - Support for flexible conflict resolution policies. - Preservation of bitwise operators.
Functions¶
__new__(metacls, cls, bases, classdict, *, conflict_enum_cls=ConflictResolution, conflict=ConflictResolution.RHS, boundary=None, _simple=False, **kwds)
¶Create a new enum class with exclusive flag support.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
metacls
|
type[EnumPlusType]
|
The metaclass being used to create the new class. |
required |
cls
|
str
|
The name of the enum class being created. |
required |
bases
|
tuple[type, ...]
|
Base classes for the new enum class. |
required |
classdict
|
dict[str, Any]
|
Dictionary containing the class attributes and methods. |
required |
conflict_enum_cls
|
type[Enum]
|
Enum class defining conflict resolution strategies. |
ConflictResolution
|
conflict
|
Enum | str
|
The conflict resolution strategy to use, either an enum value or string that can be converted to one. |
RHS
|
boundary
|
Any
|
Boundary handling for flag values (passed to EnumType). |
None
|
_simple
|
bool
|
Whether this is a simple enum (passed to EnumType). |
False
|
**kwds
|
Any
|
Additional keyword arguments passed to parent metaclass. |
{}
|
Returns:
Type | Description |
---|---|
type
|
The newly created enum class with exclusive flag support. |
Raises:
Type | Description |
---|---|
TypeError
|
If the conflict resolution strategy is invalid or not implemented. |
restore_new_members(bases)
staticmethod
¶Restore original new methods from new_member attributes.
This method handles the temporary replacement of new methods during enum creation, storing the original methods for later restoration.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bases
|
tuple[type, ...]
|
Tuple of base classes to examine for new_member attributes. |
required |
Returns:
Type | Description |
---|---|
dict[type, Callable[..., Any] | None]
|
Dictionary mapping base classes to their original new methods. |
dict[type, Callable[..., Any] | None]
|
Values may be None if no original new method existed. |
restore_news(replaced_new_methods)
staticmethod
¶Restore previously saved new methods to their original classes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
replaced_new_methods
|
dict[type, Callable[..., Any] | None]
|
Dictionary mapping classes to their original new methods that should be restored. |
required |
ValueAliasShim
¶
A mixin-style class to provide add_value_alias to Pythons < 3.13.
This is tricky. To set this on the enum class before member creation, I'd have to override EnumDict.setitem. I could set this as a dunder and then alias the 3.13+ sunder version and just have a different API than standard enums, but I think this is the best approach. This version of add_value_alias is a slightly lobotomized copy of the Python version, without the ability to handle unhashable values, as that was a mess before 3.13.
Functions¶
traverse_bases(bases)
¶
Traverse base classes to get an ordered list of the inheritance tree.
This function examines the method resolution order (MRO) of all base classes and returns a deduplicated, ordered tuple of all classes in the hierarchy.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bases
|
tuple[type, ...]
|
Tuple of base classes to traverse. |
required |
Returns:
Type | Description |
---|---|
type
|
Ordered tuple of all classes in the inheritance hierarchy, excluding |
...
|
the built-in object class. |
rebind_method(target_name, target_cls, src_method, src_cls=None)
¶
Rebind a method from one class to another with a new name.
This function creates a new method on the target class by copying a method from a source class or using a provided method object. The new method maintains the same functionality but can have a different name.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target_name
|
str
|
The name to give the method in the target class. |
required |
target_cls
|
type
|
The class to which the method should be bound. |
required |
src_method
|
classmethod | staticmethod | Callable[..., Any] | str
|
The source method to copy. Can be: - A classmethod or staticmethod decorator - A callable function - A string name of a method (requires src_cls) |
required |
src_cls
|
type | None
|
The source class containing the method (required if src_method is a string). |
None
|
Raises:
Type | Description |
---|---|
ValueError
|
If src_method is a string but src_cls is not provided, if the method name is not found in src_cls, or if src_method is not a valid object. |
TypeError
|
If src_method is not callable or doesn't have the required function attributes. |