[issue35512] patch.dict resolves in_dict eagerly (should be late resolved)
Karthikeyan Singaravelan
report at bugs.python.org
Fri Feb 22 07:32:29 EST 2019
Karthikeyan Singaravelan <tir.karthi at gmail.com> added the comment:
If I understand the issue correctly it's as below is a simple reproducer where target is resolved with {'a': 1} during the construction of the decorator [0] though it's redefined later in the program as target = dict(a=2). Also here due to this since target is reassigned the decorator just stores a reference to {'a': 1} and updates it with {'b': 2} leaving the reference to dict object {'a': 2} unpatched in test_with_decorator. Meanwhile in case of the context manager (test_with_context_manager) it's created and resolved at the time it's executed hence updating the object {'a': 2} correctly. A possible fix would be to store the reference to the string path of the patch '__main__.target' and try it again with importer function. I will take a further look into this. It would be helpful if you can confirm this reproducer is good enough and resembles the original report.
from unittest import mock
target = dict(a=1)
@mock.patch.dict('__main__.target', dict(b=2))
def test_with_decorator():
print(f"target inside decorator : {target}")
def test_with_context_manager():
with mock.patch.dict('__main__.target', dict(b=2)):
print(f"target inside context : {target}")
target = dict(a=2)
test_with_decorator()
test_with_context_manager()
$ python3 test_foo.py
target inside decorator : {'a': 2}
target inside context : {'a': 2, 'b': 2}
[0] https://github.com/python/cpython/blob/3208880f1c72800bacf94a2045fcb0436702c7a1/Lib/unittest/mock.py#L1624
----------
nosy: +xtreak
type: -> behavior
versions: +Python 3.8
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue35512>
_______________________________________
More information about the Python-bugs-list
mailing list