AutoEnum API Reference¶
Fast fuzzy-matched enums with aliases and type safety.
alias
¶
Bases: auto
Create an alias for AutoEnum members with fuzzy matching support.
Source code in src/morphic/autoenum.py
AutoEnum
¶
Bases: str, Enum
Ultra-fast AutoEnum with fuzzy matching, aliases, and collection conversion.
AutoEnum provides powerful string-to-enum conversion with case-insensitive matching, automatic normalization, and comprehensive alias support. Optimized for performance with O(1) lookups and thread-safe initialization.
Features: - Ultra-fast lookups: O(1) performance with cached normalization - Fuzzy matching: Case-insensitive with space/dash/underscore normalization - Rich aliases: Multiple aliases per enum member with fuzzy matching - Collection conversion: Convert lists, dicts, and sets between strings and enums - Display names: Human-readable formatting for UI display - Thread-safe: Safe concurrent access and initialization - Type safety: Full typing support with IDE integration
Basic Usage
from morphic import AutoEnum, alias, auto
class Priority(AutoEnum):
HIGH = alias("urgent", "critical", "high_priority")
MEDIUM = alias("normal", "standard", "medium_priority")
LOW = alias("minor", "low_priority")
# Direct string conversion with fuzzy matching
p1 = Priority("high") # HIGH
p2 = Priority("URGENT") # HIGH (alias, case insensitive)
p3 = Priority("high-priority") # HIGH (fuzzy matching)
p4 = Priority("Normal") # MEDIUM (alias, case insensitive)
# Safe conversion with error handling
p5 = Priority.from_str("invalid", raise_error=False) # None
p6 = Priority.from_str("critical") # HIGH
# Check membership and matching
assert Priority.matches_any("urgent") # True
assert Priority.HIGH.matches("CRITICAL") # True
assert not Priority.matches_any("invalid") # False
Advanced Features
# Collection conversion methods
status_strings = ["high", "normal", "urgent", "minor"]
statuses = Priority.convert_list(status_strings)
# Result: [Priority.HIGH, Priority.MEDIUM, Priority.HIGH, Priority.LOW]
# Dictionary key/value conversion
counts = {"high": 10, "normal": 25, "low": 5}
enum_counts = Priority.convert_keys(counts)
# Result: {Priority.HIGH: 10, Priority.MEDIUM: 25, Priority.LOW: 5}
# Display names for UI
for priority in Priority:
print(f"{priority}: {priority.display_name()}")
# Output:
# HIGH: High
# MEDIUM: Medium
# LOW: Low
# Custom display formatting
print(Priority.HIGH.display_name(sep="-")) # "High"
print(Priority.display_names()) # ["High", "Medium", "Low"]
# Dynamic enum creation
Color = AutoEnum.create("Color", ["red", "green grass", "Blue33"])
red = Color("red") # Color.Red
green = Color("green grass") # Color.Green_Grass
blue = Color("Blue33") # Color.Blue33
# Performance characteristics
# - 1M+ lookups per second with warm cache
# - Thread-safe initialization and access
# - Consistent O(1) performance regardless of enum size
String Normalization
AutoEnum automatically normalizes strings by: - Converting to lowercase - Removing spaces, dashes, underscores, dots, colons, semicolons, commas - Handling various naming conventions automatically
class Protocol(AutoEnum):
HTTP_SECURE = alias("HTTPS", "http-secure", "HTTP Secure")
# All variations work due to normalization
p1 = Protocol("HTTP-SECURE") # HTTP_SECURE
p2 = Protocol("http_secure") # HTTP_SECURE
p3 = Protocol("HTTP Secure") # HTTP_SECURE
p4 = Protocol("httpsecure") # HTTP_SECURE (spaces removed)
Error Handling
try:
status = Priority("invalid_priority")
except ValueError as e:
print(f"Error: {e}")
# Output: Could not find enum with value 'invalid_priority';
# available: ['HIGH', 'MEDIUM', 'LOW']
# Safe conversion patterns
def safe_priority(value: str) -> Optional[Priority]:
return Priority.from_str(value, raise_error=False)
priority = safe_priority("maybe_valid") # Returns None if invalid
if priority:
print(f"Valid priority: {priority}")
Source code in src/morphic/autoenum.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 | |
from_str(enum_value: Any, raise_error: bool = True) -> Optional[AutoEnum]
classmethod
¶
Convert string to AutoEnum with fuzzy matching.
Source code in src/morphic/autoenum.py
matches(enum_value: str) -> bool
¶
matches_any(enum_value: str) -> bool
classmethod
¶
does_not_match_any(enum_value: str) -> bool
classmethod
¶
display_names(**kwargs) -> str
classmethod
¶
display_name(*, sep: str = ' ') -> str
¶
Get human-readable display name for this enum member.
convert_keys(d: Dict) -> Dict
classmethod
¶
Convert string dictionary keys to enum values where possible.
Source code in src/morphic/autoenum.py
convert_keys_to_str(d: Dict) -> Dict
classmethod
¶
convert_values(d: Union[Dict, Set, List, Tuple], raise_error: bool = False) -> Union[Dict, Set, List, Tuple]
classmethod
¶
Convert string values to enum values where possible.
Source code in src/morphic/autoenum.py
convert_dict_values(d: Dict) -> Dict
classmethod
¶
Convert string dictionary values to enum values where possible.
convert_list(l: List) -> List
classmethod
¶
Convert string list items to enum values where possible.
convert_set(s: Set) -> Set
classmethod
¶
Convert string set items to enum values where possible.
Source code in src/morphic/autoenum.py
convert_values_to_str(d: Dict) -> Dict
classmethod
¶
create(name: str, values: List[str]) -> type[AutoEnum]
staticmethod
¶
Dynamically creates an AutoEnum subclass named name from a list of strings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name for the new enum class |
required |
values
|
List[str]
|
List of string values to become enum members |
required |
Returns:
| Type | Description |
|---|---|
type[AutoEnum]
|
A new AutoEnum subclass |
Example
Status = AutoEnum.create('Status', ['pending', 'running', 'complete'])