Home > Software engineering >  How can I define default values using context manger in Python
How can I define default values using context manger in Python

Time:10-21

Is it possible to do something like:

class A:
    def __init__(self, attr):
        self.attr = attr

default_attr = 5
with B(default_attr):
    a = A()

assert a.attr == default_attr

CodePudding user response:

you could use unittest.mock's patch as follows:

from contextlib import contextmanager
from unittest.mock import patch


@contextmanager
def default(class_, *args, **kwargs):
    init = class_.__init__
    with patch.object(class_, "__init__", lambda self: init(self, *args, **kwargs)):
        yield class_


class A:
    def __init__(self, attr):
        self.attr = attr


if __name__ == "__main__":
    default_attr = 5

    with default(A, attr=default_attr):
        a = A()
    assert a.attr == default_attr

  • Related