S3Generic
S3Generic(name, default=None, doc='')A callable that dispatches to a registered method based on the type of its first argument, with a user-supplied default fallback.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| name | str | The name of the generic (used in error messages). | required |
| default | callable | Default implementation called when no specific method is registered for the argument’s type. Receives (obj, *args, **kwargs). |
None |
| doc | str | Docstring appended to the auto-generated signature line. | '' |
Examples
>>> from s3generics import S3Generic
>>> summary = S3Generic("summary")
>>>
>>> @summary.register(list)
... def _summary_list(obj, *args, **kwargs):
... print(f"list of length {len(obj)}")
>>>
>>> summary([1, 2, 3])
list of length 3Methods
| Name | Description |
|---|---|
| dispatch | Return the best-matching method for obj without calling it. |
| methods | Return {type_name: callable} for all registered methods. |
| register | Decorator that registers a method for one or more types. |
| register_for | Imperative (non-decorator) registration. |
dispatch
S3Generic.dispatch(obj)Return the best-matching method for obj without calling it.
methods
S3Generic.methods()Return {type_name: callable} for all registered methods.
register
S3Generic.register(*types)Decorator that registers a method for one or more types.
from s3generics import S3Generic summary = S3Generic(“summary”)
class MyClass: … def init(self, data): … self.data = data … @summary.register(MyClass) … def _summary_myclass(obj, **kw): …
register_for
S3Generic.register_for(fn, *types)Imperative (non-decorator) registration.