3

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?

forvas
  • 9,801
  • 7
  • 62
  • 158

1 Answers1

3

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
Charif DZ
  • 14,415
  • 3
  • 21
  • 40
  • Your workaround works perfectly. I'd like to have another cleaner solution, but I guess I'm not going to find it and may be there aren't even any simplier and cleaner solutions than yours. Thank you very much @Cherif. – forvas Mar 02 '18 at 09:16
  • 1
    I think there is may be we need to update the class it self, python support multiple inheriting. So if you modify the class it self to inherit the new class. I'm saying this because odoo do the same he create a class object from all the classess that contains all fields and methods i think i'm steel figuring python what a powerful language you can do what ever you want with it. Updating the class in runtime is the second solution don't you think so. – Charif DZ Mar 02 '18 at 09:40