Dynamically Mix in Methods into An Instance in Python

As Python is a dynamic language it offers many possibilities how to manipulate object instances during runtime.   We may for instance inject methods from another class,  achieving similar results as  if  this instance has this calls as a mix-in super class. This approach could be useful to hack some existing libraries with extra functionality, in case we have to work with created  instances.

This function will inject methods from mixin_class into instance assuring that method is properly bound to the instance.

import types

def mixin(instance, mixin_class):
    """Dynamic mixin of methods into instance - works only for new style classes"""
    for name in mixin_class.__dict__:
        if name.startswith('__') and name.endswith('__') \
        or not  type(mixin_class.__dict__[name])==types.FunctionType:
            continue

        instance.__dict__[name]=mixin_class.__dict__[name].__get__(instance)

Continue reading Dynamically Mix in Methods into An Instance in Python

Django tests auto-discover

Django framework  provides integrated tests runner, which can be started by ./manage/py test (see docs for more details, key advantage of this runner is that it’ll create new empty database for tests, so they do not interfere with each other or your development instance).   This tests runner runs unit tests from tests.py or models.py modules in active projects.  However in larger projects we would like to have other organization of tests code –   have for instance special test package within project that  contains many testing modules, each focused on particular aspect of the application. Continue reading Django tests auto-discover