binding
File Purpose: binding functions to already-existing classes
Motivation: it is convenient to be able to add many functions to classes after their creation.
This facilitates a useful design principle:
- when creating a class, only define a minimal set of behaviors.
- when adding new behaviors to an existing class, bind new attributes/methods to the class,
OUTSIDE of the class definition, rather than editing the class defintion directly.
Usually it is sufficient to use this module in the following way:
from binding_module import Binding
binding = Binding(locals())
class MyClass(…):
# this class could be defined here, or literally anywhere else.
# e.g. “from module_with_class import MyClass” is fine too.
with binding.to(MyClass):
@binding
def foo1(self, *args, **kw): # any signature is fine, e.g. foo1(self, x) is fine too.
# < code for foo1 goes here
@binding
def foo2(self, *args, **kw):
# < code for foo2 goes here
# … can define any number of functions using @binding
print(MyClass.foo1)
–> (info about the bound method foo1 of MyClass, defined above)
print(foo1)
–> (NameError; foo1 is undefined in this namespace after exiting the ‘with’ block.)
It is also possible to keep a local copy(s) to the defined function(s),
or to bind them as staticmethod or classmethod. See help(Binding) for details.
Functions
|
returns a function decorator which binds f to target.(f.__name__) for target in targets. |
Classes
|
context manager for binding environment. |