Question

I would like to wrap class of an existing huge package like for example matplotlib but my wrapper will not implement all the method. For example, in my MWE, I would to raise an exception to say that the class Bidon2 has not implemented method_2.

My problem is that the module not necessarily implements a system of abstract class. Is there a way to fix that ?

module.py

#!/usr/bin/env python3

class Bidon():
    def method_1(self):
        print('Method 1')

    def method_2(self):
        print('Method 2')

wrapper.py

#!/usr/bin/env python3

import module

class Bidon2(module.Bidon):
    def method_1(self):
        print('New Method 1')


Bidon2().method_1()

Bidon().method_2()

Output

New Method 1
Method 2
Was it helpful?

Solution

This is kind of ugly, but it works. Basically, you can use dir to get a full list of all attributes/methods supported by this class. Then, you can use the class __dict__ to get what's actually defined in that class itself. Below, for any attr that's defined in the base class and not actually defined in the current class, we monkey-patch it to point at our own routine to raise an exception.

class Bidon2(Bidon):
    def method_1(self):
        print 'New method 1'
    def raise_attr_error(self):
        raise AttributeError, 'Attribute not supported!'
    def __init__(self):
        all_funcs = [x for x in dir(self) if not x.startswith('_')]
        all_funcs = [x for x in all_funcs if x not in Bidon2.__dict__]
        for x in all_funcs:
            setattr(self, x, self.raise_attr_error)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top