简体   繁体   中英

How can I detect when someone changes a python dict (and/or object)?

We have some unittests (a few out of several 1000) that are modifying pytest fixtures which leads to tests that fail for no apparent reason. We are running pytest -n 8 and the order of test execution isn't important to us (faster is better), but when one of these misbehaving tests comes in front of something that relies on that part of a fixture, we get a random unittest failure.

Is there some way to either make an object/dict immutable, or some way to raise an exception when that object is changed so that I can catch the offender in the act?

I'm wanting to protect something like this:

settings = load_settings(....)
settings = protect_settings(settings)

It seems sort of like the mock library with introspection for the capabilities of the object and then mirroring the actual actions with some exception throwing for the set actions. I'm hoping this has already been built.

We are still on python2.7 :-(

There is a simple implementation of a FrozeDict here . You could use this and you will get an error when you want to modify it as there is no __setitem__ method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM