Registry API Reference¶
Registry pattern for automatic class registration and retrieval.
Registry
¶
Bases: ABC
Inheritance-based class registration system with hierarchical factory pattern.
Registry automatically registers classes through inheritance and provides sophisticated factory methods for instance creation. Classes automatically register themselves when they inherit from Registry subclasses, and the system provides hierarchical factory methods that respect class inheritance relationships.
Features
- Automatic Registration: Classes auto-register when inheriting from Registry
- Hierarchical Factory Pattern: Three-tier intelligent instantiation
- Scoped Lookups: Each class can only instantiate its own subclasses
- Class Aliases: Multiple names for the same class
- Custom Registry Keys: Flexible key systems including tuples
- String Normalization: Case-insensitive, flexible key matching
- Registry Inspection: Query available classes and hierarchies
Hierarchical Factory Pattern
The Registry provides three intelligent instantiation modes:
-
Direct Instantiation (Concrete Classes): Concrete classes can be instantiated directly without registry keys
-
Factory Method (Abstract Classes): Abstract classes require registry keys and search within their hierarchy
-
Hierarchical Scoping: Classes can only instantiate their own subclasses, enforcing hierarchy
Basic Usage
from morphic.registry import Registry
from abc import ABC, abstractmethod
# Base registry class
class Animal(Registry, ABC):
@abstractmethod
def speak(self) -> str:
pass
# Classes automatically register when inheriting
class Dog(Animal):
aliases = ["canine", "pup"] # Multiple aliases supported
def __init__(self, name: str = "Buddy"):
self.name = name
def speak(self) -> str:
return f"{self.name} says Woof!"
class Cat(Animal):
aliases = ["feline", "kitty"]
def __init__(self, name: str = "Whiskers"):
self.name = name
def speak(self) -> str:
return f"{self.name} says Meow!"
# Hierarchical factory usage examples
dog = Dog.of(name="Rex") # Direct concrete instantiation
cat = Animal.of("Cat", name="Fluffy") # Factory with class name
feline = Animal.of("feline", name="Shadow") # Using alias
pup = Animal.of("pup", name="Buddy") # Case-insensitive fuzzy matching
# String normalization works automatically
canine = Animal.of("CANINE", name="Max") # Case insensitive
dog2 = Animal.of("ca-nine", name="Rex") # Handles dashes/spaces
print(dog.speak()) # "Rex says Woof!"
print(cat.speak()) # "Fluffy says Meow!"
Advanced Features
# Class aliases for flexible naming
class DatabaseConnection(Registry):
aliases = ["db", "database", "connection"]
# Multiple ways to create the same object
db1 = DatabaseConnection.of() # Direct concrete instantiation
db2 = DatabaseConnection.of("db", host="remote") # Using alias
db3 = DatabaseConnection.of("DATABASE") # Case insensitive
# Custom registry keys with _registry_keys method
class HTTPSService(Registry):
@classmethod
def _registry_keys(cls):
return [
("protocol", "https"), # Tuple key
("service", "web"), # Another tuple key
8443, # Numeric key
"secure_web" # String key
]
# Create using different key types
service1 = HTTPSService.of(("protocol", "https")) # Tuple key
service2 = HTTPSService.of(8443) # Numeric key
service3 = HTTPSService.of("secure_web") # String key
# Registry inspection for discovery
available_classes = DatabaseConnection.subclasses() # Get all concrete subclasses
class_by_key = DatabaseConnection.get_subclass("db") # Get class by key
all_keys = list(DatabaseConnection._registry.keys()) # All registered keys
# Error handling with hierarchical scoping
try:
service = WrongHierarchy.of("SomeClass") # KeyError with available options
except KeyError as e:
print(f"Available in hierarchy: {e}")
Hierarchical Architecture
class Service(Registry, ABC):
pass
class DataService(Service, ABC):
pass
class NotificationService(Service, ABC):
pass
class FileService(DataService):
pass
class EmailService(NotificationService):
pass
# Hierarchical scoping enforced
file_svc = DataService.of("FileService") # ✅ Works
email_svc = NotificationService.of("EmailService") # ✅ Works
any_svc = Service.of("EmailService") # ✅ Works (common base)
# email_svc = DataService.of("EmailService") # ❌ Wrong hierarchy
Registry Inspection
Query and explore the registry:
# Get all subclasses
animal_types = Animal.subclasses() # Concrete classes only
all_animals = Animal.subclasses(keep_abstract=True) # Include abstract
# Get specific class by key
dog_class = Animal.get_subclass("Dog") # Returns Dog class
cat_class = Animal.get_subclass("feline") # Using alias
# Check what's available
available_keys = list(Animal._registry.keys())
Error Handling
The Registry provides clear error messages for common issues:
TypeError: Calling Registry.of() directly or abstract class without keyKeyError: Registry key not found in hierarchyTypeError: Multiple subclasses registered to same key (when not allowed)
Performance Notes
- Key lookups are O(1) hash table operations
- String normalization happens once during registration
- Hierarchical filtering is optimized for inheritance chains
- Each registry hierarchy maintains its own lookup table
- Minimal memory overhead per registered class
See Also
of(): Hierarchical factory method for instance creationget_subclass(): Get class by key without creating instancesubclasses(): Get all registered subclassesremove_subclass(): Remove class from registry
Source code in src/morphic/registry.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 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 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 | |
get_subclass(key: Any, raise_error: bool = True) -> Optional[Union[Type, List[Type]]]
classmethod
¶
Get registered subclass(es) by key without creating instances.
This method performs a global registry lookup (not hierarchical) to find all subclasses
registered under the given key. Unlike the hierarchical of() method, this searches
the entire registry without scoping restrictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
Key to look up subclass. Can be: - str: Class name or alias (case-insensitive, normalized) - tuple: Custom composite key from _registry_keys() - Any: Custom key type from _registry_keys() |
required |
raise_error
|
bool
|
Whether to raise KeyError if key not found. Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
Optional[Union[Type, List[Type]]]
|
|
Optional[Union[Type, List[Type]]]
|
|
Optional[Union[Type, List[Type]]]
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If key not found and raise_error=True |
Examples:
class Animal(Registry, ABC):
pass
class Dog(Animal):
aliases = ["canine", "pup"]
class Cat(Animal):
aliases = ["feline"]
# Get class by name
DogClass = Animal.get_subclass("Dog")
assert DogClass is Dog
# Get class by alias
CanineClass = Animal.get_subclass("canine")
assert CanineClass is Dog
# Case insensitive
CatClass = Animal.get_subclass("FELINE")
assert CatClass is Cat
# Handle missing keys
UnknownClass = Animal.get_subclass("Robot", raise_error=False)
assert UnknownClass is None
try:
Animal.get_subclass("Robot") # raise_error=True by default
except KeyError:
print("Robot not found")
Note
This method searches the entire registry and does not enforce hierarchical
scoping like the of() method. Use of() for hierarchy-aware instantiation.
Source code in src/morphic/registry.py
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 | |
subclasses(keep_abstract: bool = False) -> Set[Type]
classmethod
¶
Get all registered subclasses of this Registry class.
Returns all classes that have been registered as subclasses of the calling class. This provides a way to discover what implementations are available without needing to know their keys in advance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keep_abstract
|
bool
|
Whether to include abstract classes in the result. Defaults to False (only concrete classes returned). |
False
|
Returns:
| Type | Description |
|---|---|
Set[Type]
|
Set[Type]: Set of registered subclass types. Abstract classes are excluded |
Set[Type]
|
unless keep_abstract=True. |
Examples:
class Animal(Registry, ABC):
pass
class Mammal(Animal, ABC): # Abstract intermediate
pass
class Dog(Mammal):
pass
class Cat(Mammal):
pass
class Bird(Animal, ABC): # Abstract intermediate
pass
class Parrot(Bird):
pass
# Get concrete subclasses only (default)
concrete_animals = Animal.subclasses()
assert Dog in concrete_animals
assert Cat in concrete_animals
assert Parrot in concrete_animals
assert Mammal not in concrete_animals # Abstract
assert Bird not in concrete_animals # Abstract
# Include abstract classes
all_animals = Animal.subclasses(keep_abstract=True)
assert Mammal in all_animals
assert Bird in all_animals
assert Dog in all_animals
# Hierarchical subclasses
mammals = Mammal.subclasses() # Only mammal subclasses
assert Dog in mammals
assert Cat in mammals
assert Parrot not in mammals # Not a mammal
Use Cases
- Plugin Discovery: Find all available plugin implementations
- Validation: Check what implementations are registered
- Dynamic UI: Build menus or lists of available options
- Testing: Verify all expected subclasses are registered
- Documentation: Generate lists of available classes
# Plugin discovery example
available_processors = DataProcessor.subclasses()
for processor_cls in available_processors:
print(f"Available: {processor_cls.__name__}")
if hasattr(processor_cls, 'aliases'):
print(f" Aliases: {processor_cls.aliases}")
# Dynamic factory with validation
def create_safe_processor(processor_type: str, **kwargs):
available = {cls.__name__.lower(): cls for cls in DataProcessor.subclasses()}
if processor_type.lower() not in available:
raise ValueError(f"Unknown processor: {processor_type}. "
f"Available: {list(available.keys())}")
return available[processor_type.lower()](**kwargs)
Note
This method respects the registry hierarchy - it only returns subclasses of the calling class, not subclasses of sibling classes.
Source code in src/morphic/registry.py
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 | |
remove_subclass(subclass: Union[Type, str])
classmethod
¶
Remove a subclass from the registry.
Source code in src/morphic/registry.py
of(registry_key: Optional[Any] = None, *args, **kwargs)
classmethod
¶
Hierarchical factory method for creating instances of registered subclasses.
This is the core factory method that provides intelligent, hierarchy-aware instance creation. The behavior depends on whether the calling class is abstract or concrete, and whether a registry_key is provided. The method enforces hierarchical scoping - classes can only instantiate their own subclasses.
Hierarchical Factory Modes:
**1. Direct Instantiation (Concrete Classes):**
Concrete classes can create instances directly without registry keys:
```python
class Dog(Animal): # Concrete class
def __init__(self, name="Buddy"):
self.name = name
dog = Dog.of() # ✅ Direct instantiation
dog = Dog.of(name="Rex") # ✅ With constructor args
dog = Dog.of("Dog", name="Max") # ✅ Also works with matching key
```
**2. Factory Method (Abstract Classes):**
Abstract classes require registry keys to specify which subclass to create:
```python
class Animal(Registry, ABC): # Abstract base
pass
dog = Animal.of("Dog", name="Buddy") # ✅ Key required
cat = Animal.of("Cat", name="Whiskers") # ✅ Key required
# animal = Animal.of() # ❌ TypeError: key required
```
**3. Hierarchical Scoping:**
Classes can only instantiate their own subclasses, enforcing architecture:
```python
class Mammal(Animal, ABC):
pass
class Cat(Mammal, ABC):
pass
class Dog(Mammal):
pass
class TabbyCat(Cat):
pass
# Hierarchical restrictions enforced
tabby = Cat.of("TabbyCat") # ✅ TabbyCat is Cat subclass
dog = Mammal.of("Dog") # ✅ Dog is Mammal subclass
any_animal = Animal.of("Dog") # ✅ Dog is Animal subclass
# dog = Cat.of("Dog") # ❌ KeyError: Dog not Cat subclass
```
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry_key
|
Any
|
Key to look up subclass. Can be: - None: For concrete classes, instantiates the class directly - str: Class name or alias (case-insensitive, normalized) - tuple: Custom composite key from _registry_keys() - Any: Custom key type from _registry_keys() If None and the class is concrete, instantiates that class directly. If None and the class is abstract, raises TypeError. |
None
|
*args
|
Positional arguments passed to the subclass constructor |
()
|
|
**kwargs
|
Keyword arguments passed to the subclass constructor |
{}
|
Returns:
| Type | Description |
|---|---|
|
Instance of the found subclass or the class itself (for direct instantiation) |
Raises:
| Type | Description |
|---|---|
TypeError
|
If called on Registry base class directly, or if abstract class called without registry_key, or multiple subclasses match key |
KeyError
|
If registry_key not found in the class's hierarchy |
Registry Key Types
# String keys (normalized: case-insensitive, space/dash/underscore flexible)
service = Service.of("EmailService")
service = Service.of("email-service") # Same as above
service = Service.of("EMAIL_SERVICE") # Same as above
# Alias keys
class EmailService(Service):
aliases = ["email", "mail", "smtp"]
service = Service.of("email") # Using alias
# Tuple keys from _registry_keys()
class HTTPService(Service):
@classmethod
def _registry_keys(cls):
return [("protocol", "http"), ("service", "web")]
service = Service.of(("protocol", "http"))
service = Service.of(("service", "web"))
# Direct instantiation (concrete classes only)
service = EmailService.of() # No key needed
Hierarchical Architecture Example
class Service(Registry, ABC):
@abstractmethod
def process(self, data): pass
class DataService(Service, ABC):
'''Base for data processing services'''
pass
class NotificationService(Service, ABC):
'''Base for notification services'''
pass
class FileService(DataService):
def process(self, data):
return f"Processing file: {data}"
class EmailService(NotificationService):
aliases = ["email", "mail"]
def process(self, data):
return f"Sending email: {data}"
class SMSService(NotificationService):
def process(self, data):
return f"Sending SMS: {data}"
# Hierarchical scoping in action
file_svc = DataService.of("FileService") # ✅ FileService ∈ DataService
email_svc = NotificationService.of("EmailService") # ✅ EmailService ∈ NotificationService
mail_svc = NotificationService.of("mail") # ✅ Using alias
any_svc = Service.of("SMSService") # ✅ SMSService ∈ Service
# These fail due to hierarchical restrictions
# email_svc = DataService.of("EmailService") # ❌ EmailService ∉ DataService
# file_svc = NotificationService.of("FileService") # ❌ FileService ∉ NotificationService
# Direct instantiation for concrete classes
file_svc = FileService.of() # ✅ Direct concrete instantiation
email_svc = EmailService.of(smtp_host="smtp.com") # ✅ With constructor args
Error Handling
# Registry base class usage
try:
Registry.of("SomeClass")
except TypeError as e:
# "The 'of' factory method cannot be called directly on Registry class"
# Abstract class without key
try:
Service.of() # Abstract class, no key
except TypeError as e:
# "Cannot instantiate abstract class 'Service' without specifying a registry_key"
# Key not found in hierarchy
try:
DataService.of("EmailService") # EmailService not in DataService hierarchy
except KeyError as e:
# "Could not find subclass of DataService using registry_key: 'EmailService'"
# Shows available keys in DataService hierarchy
# Multiple subclasses (when _allow_multiple_subclasses=True)
try:
Service.of("shared_alias") # Multiple classes have same alias
except TypeError as e:
# "Cannot instantiate using registry_key 'shared_alias' because multiple subclasses"
Performance Notes
- Registry lookups are O(1) hash table operations
- Hierarchical filtering is optimized for inheritance chains
- String normalization is cached during registration
- Direct instantiation (concrete classes) bypasses registry lookup entirely
See Also
get_subclass(): Get class by key without creating instance subclasses(): Get all registered subclasses in hierarchy _get_hierarchical_subclass(): Internal hierarchical lookup method
Source code in src/morphic/registry.py
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 | |