Package: extendable
ExtendableAboutExtendable is a module that aims to provide a way to define extensible python
classes. It is designed to provide developers with a convenient and flexible way
to extend the functionality of their Python applications. By leveraging the "extendable"
library, developers can easily create modular and customizable components that
can be added or modified without modifying the core codebase. This library utilizes
Python's object-oriented programming features and provides a simple and intuitive
interface for extending and customizing applications. It aims to enhance code
reusability, maintainability, and overall development efficiency. It implements
the extension by inheritance and composition pattern. It's inspired by the way
odoo implements its models. Others patterns can be used to make your code pluggable
and this library doesn't replace them.Quick startLet's define a first python class.fromextendableimportExtendableMetaclassPerson(metaclass=ExtendableMeta):def__init__(self,name:str):self.name=namedef__repr__(self)->str:returnself.nameSomeone using the module where the class is defined would need to extend the
person definition with a firstname field.fromextendableimportExtendableMetaclassPersonExt(Person,extends=Person):def__init__(self,name:str):super().__init__(name)self._firstname=None@propertydeffirstname(self)->str:returnself._firstname@firstname.setterdeffirstname(self,value:str)->None:self._firstname=valuedef__repr__(self)->str:res=super().__repr__()returnf"{res},{self.firstnameor''}"At this time we have defined thatPersonExtextends the initial definition
ofPerson. To finalyse the process, we need to instruct the runtime that
all our class declarations are done by building the final class definitions and
making it available into the current execution context.fromextendableimportcontext,registry_registry=registry.ExtendableClassesRegistry()context.extendable_registry.set(_registry)_registry.init_registry()Once it's done thePersonandPersonExtclasses can be used interchangeably
into your code since both represent the same class...p=Person("Mignon")p.firstname="Laurent"print(p)#> Mignon, Laurent:warning: This way of extending a predefined behaviour must be used carefully and in
accordance with theLiskov substitution principleIt doesn't replace others design patterns that can be used to make your code pluggable.How it worksBehind the scenes, the "extendable" library utilizes several key concepts and
mechanisms to enable its functionality. Overall, the "extendable" library leverages
metaclasses, registry initialization, and dynamic loading to provide a flexible
and modular approach to extending Python classes. By utilizing these mechanisms,
developers can easily enhance the functionality of their applications without
the need for extensive modifications to the core codebase.MetaclassesThe metaclass do 2 things.It collects the definitions of the declared class and gathers information about
its attributes, methods, and other characteristics. These definitions are stored
in a global registry by module. This registry is a map of module name to a list
of class definitions.This information is then used to build a class object that acts as a proxy or
blueprint for the actual concrete class that will be created later when the registry
is initialized based on the aggregated definition of all the classes declared
to extend the initial class...Registry initializationThe registry initialization is the process that build the final class definition.
To make your blueprint class work, you need to initialize the registry. This is
done by calling theinit_registrymethod of the registry object. This method
will build the final class definition by aggregating all the definitions of the
classes declared to extend the initial class through a class hierarchy. The
order of the classes in the hierarchy is important. This order is by default
the order in which the classes are loaded by the python interpreter. For advanced
usage, you can change this order or even the list of definitions used to build the
final class definition. This is done by calling theinit_registrymethod with
the list of modules[^1] to load as argument.[^1]: When you specify a module into the list of modules to load, the wildcart
character*is allowed at the end of the module name to load all the
submodules of the module. Otherwise, only the module itself is loaded.fromextendableimportregistry_registry=registry.ExtendableClassesRegistry()_registry.init_registry(["module1","module2.*"])Once the registry is initialized, it must be made available into the current
execution context so the blueprint class can use it. To do so you must set the
registry into theextendable_registrycontext variable. This is done by
calling thesetmethod of theextendable_registrycontext variable.fromextendableimportcontext,registry_registry=registry.ExtendableClassesRegistry()context.extendable_registry.set(_registry)_registry.init_registry()Dynamic loadingAll of this is made possible by the dynamic loading capabilities of Python.
The concept of dynamic loading in Python refers to the ability to load and execute
code at runtime, rather than during the initial compilation or execution phase.
It allows developers to dynamically import and use modules, classes, functions
or variables based on certain conditions or user input. The dynamic loading
can also be applied at class instantiation time. This is the mechanism used by
the "extendable" library to instantiate the final class definition when you call
the constructor of the blueprint class. This is done by implementing the__call__method into the metaclass to return the final class definition instead
of the blueprint class itself. The same applies to pretend that the blueprint
class is the final class definition through the implementation of the__subclasscheck__method into the metaclass.DevelopmentTo run tests, usetox. You will get a test coverage report inhtmlcov/index.html.
An easy way to install tox ispipx install tox.This project uses pre-commit to enforce linting (among which black for code formating,
isort for sorting imports, and mypy for type checking).To make sure linters run locally on each of your commits, install pre-commit
(pipx install pre-commitis recommended), and runpre-commit installin your
local clone of the extendable repository.To release:run ``bumpversion patch|minor|major--listCheck thenew_versionvalue returned by the previous commandruntowncrier build.Inspect and commit the updated HISTORY.rst.git tag {new_version} ; git push --tags.ContributingAll kind of contributions are welcome.