Search code examples
pythonpython-2.7odoo-8odoo

How to inherit from a pure Python class in Odoo to modify a method?


I have to modify a method in Odoo. The problem is that the class which contains the method is not declared as usual (it's not using the Odoo API), so I don't know how to emulate the _inherit parameter of the Odoo API.

This is the class which contains the method (the module is account_financial_report_webkit, from OCA):

...
from openerp.addons.account.report.common_report_header \
    import common_report_header

class CommonReportHeaderWebkit(common_report_header):
    ...

And the method I want to modify is this one (it's inside CommonReportHeaderWebkit class):

def is_initial_balance_enabled(self, main_filter):
    if main_filter not in ('filter_no', 'filter_year', 'filter_period'):
        return False
    return True

To overwrite it, I did monkey patching in my custom module:

from openerp.addons.account_financial_report_webkit.report.common_reports \
    import CommonReportHeaderWebkit

def is_initial_balance_enabled(self, main_filter):
    if main_filter not in ('filter_no', 'filter_date', 'filter_period'):
        return False
    return True

CommonReportHeaderWebkit.is_initial_balance_enabled = is_initial_balance_enabled

This is working OK, but the problem is this way I'm overwriting the whole method and I would like to use super, because now I have to do the same with other method and I can't overwrite its whole code.

Does anyone know how to this in a right way?


Solution

  • I'm not an expert in python but from what i Know method can be used as object so i think this will work.

        from openerp.addons.account_financial_report_webkit.report.common_reports \
            import CommonReportHeaderWebkit
    
        # first keep reference to the original method before you lose it.
        _super_is_initial_balance_enabled = CommonReportHeaderWebkit.is_initial_balance_enabled
    
        def is_initial_balance_enabled(self, main_filter):
            # execute it like super
            return _super_is_initial_balance_enabled(self, main_filter)
    
        CommonReportHeaderWebkit.is_initial_balance_enabled = is_initial_balance_enabled