lazr.delegates
lazr.delegates provides a simple, declarative way to create Python objects that delegate behavior to other objects. It simplifies the implementation of common design patterns like composition, allowing classes to expose methods from 'delegatee' objects without boilerplate code. The current version is 2.1.1, and the library maintains a stable, albeit infrequent, release cadence, primarily focusing on Python compatibility and bug fixes.
Common errors
-
AttributeError: 'MyPet' object has no attribute 'delegated_method'
cause The `@delegates` decorator was either not applied to the class, or the class specified as the delegatee does not actually contain the method you are trying to call.fixVerify that your class is decorated with `@delegates(DelegateeClass)` and that `DelegateeClass` correctly defines the method. Also, check for typos in the method name. -
TypeError: 'module' object is not callable (when calling delegates as lazr.delegates.delegates)
cause You likely imported the `lazr.delegates` module directly using `import lazr.delegates` and then attempted to call `lazr.delegates.delegates` as if it were a function or class.fixUse a direct import statement for the `delegates` decorator: `from lazr.delegates import delegates`. Then, apply it directly: `@delegates(MyDelegatee)`. -
SyntaxWarning: lazr.delegates.delegates: 'MyClass' does not implement the delegated method 'non_existent_method'
cause This warning occurs when the class you're delegating *to* (the delegatee) does not have a method that `lazr.delegates` expects to find, often due to a typo or misunderstanding of the delegatee's API.fixInspect the `DelegateeClass` (e.g., `SoundMaker` in the quickstart) to ensure that `non_existent_method` actually exists and is spelled correctly. Adjust your code to only delegate methods that are present in the delegatee.
Warnings
- breaking Version 2.0.0 dropped support for Python 2.x and Python 3.7. The library now requires Python 3.8 or newer.
- gotcha By default, `lazr.delegates` primarily delegates methods. If you intend to delegate attributes (properties, instance variables), you need to explicitly configure the delegate type.
- gotcha When combining `lazr.delegates` with complex inheritance hierarchies, particularly multiple inheritance or explicit `super()` calls, method resolution order (MRO) can lead to unexpected behavior.
Install
-
pip install lazr-delegates
Imports
- delegates
import lazr.delegates; lazr.delegates.delegates
from lazr.delegates import delegates
- Delegate
from lazr.delegates import Delegate
Quickstart
from lazr.delegates import delegates
class SoundMaker:
def make_sound(self):
return "Woof!"
def get_animal_type(self):
return "Dog"
@delegates(SoundMaker)
class MyPet:
# MyPet now delegates make_sound and get_animal_type to SoundMaker
pass
pet = MyPet()
print(f"Pet sound: {pet.make_sound()}")
print(f"Pet type: {pet.get_animal_type()}")