Omar Silva
Omar Silva

Reputation: 120

how to modify a variable value in a Python module using inheritance

I have a class A with many methods. There is one particular method that is referring to an external variable from the module imported. I don't have control of the module. In order to work around the problem I have created a class B that inherits from class A and modified the method by removing the reference to this external value. However, this a large method that might change. Is there a way to inherit the entire class but only modify the external value from the module?

external_value = 5
class A():

    def add(self, b, c):            
        print(external_value)
        print(b+c)
        #100s of lines of code

class B(A):

    def add(self, b,c):
        print(b+c)
        #100s of lines of code


a1 = A()
a1.add(3,5)

b1 = B()
b1.add(3,5)

Upvotes: 1

Views: 126

Answers (1)

L3viathan
L3viathan

Reputation: 27273

You could use unittest.mock.patch for this:

external_module.py:

external_value = 5

class A:
    def add(self, a, b):
        print(external_value)
        print(a + b)

your_module.py:

from unittest.mock import patch
from external_module import A

class B(A):
    def add(self, *args, **kwargs):
        with patch("external_module.external_value", 99):
            return super().add(*args, **kwargs)

If you now instantiate B and call add, this happens:

>>> b = B()
>>> b.add(1, 2)
99
3

Upvotes: 1

Related Questions