python 模块的数据描述符

Data descriptors for python module

我知道您可以使用 __get____set__ 方法为 class 实例定义数据描述符。是否可以为导入的模块定义类似的东西?

用例:

我有一个很大的测试文件,其中定义了很多词典 test_data.py(遗留代码),因此它们都是**可变的,并且在不使用 deepcopy

的情况下无法通过单独的测试进行修改

我希望能够修改这些词典

  1. 无需将数据重新写入 classes
  2. 没有在测试中调用 deepcopy。

测试数据:

expected_response_1 = dict(status=False)

测试用例:

from test import test_data

data = test_data.expected_response_1
data['status'] = True

print(data)
# --> {'status': True}

print(test_data.expected_response_1)
# --> {'status': False}

有没有什么*python魔法我可以用来总是return一份expected_response_1

我认为你的意思是字典是可变的,你想在不修改原始字典的情况下更改测试用例中的字典。

你确实可以使用deepcopy,这根本不是一个坏习惯。您还可以更改 test_data 模块以将词典作为 class 属性提供:这将每次 return 一个新词典,其原始内容为:

test_data.py:

class test_data:

    @property
    @staticmethod
    def expected_response_1:
        return dict(status=False)

test_case.py:

from test.test_data import test_data

data = test_data.expected_response_1
data['status'] = True

print(data)
# --> {'status': True}

print(test_data.expected_response_1)
# --> {'status': False}

这不能直接完成,因为描述符需要定义为 class 属性(这意味着您必须将它们添加到内置 module 类型,这是不允许的)。

但是您可以在 test_data 模块周围使用一个简单的包装器并使用 __getattr__() 魔术方法:

class DataWrapper(object):
    def __init__(self, module):
        self._module = module

    def __getattr__(self, name):
        val = getattr(self._module, name)
        return copy.deepcopy(val)


from test import test_data
test_data = WrapperData(test_data)