First time writing to python-ideas.
*Overview* Add a new mock class within the mock module https://github.com/python/cpython/blob/master/Lib/unittest/mock.py, SealedMock (or RestrictedMock) that allows to restrict in a dynamic and recursive way the addition of attributes to it. The new class just defines a special attribute "sealed" which once set to True the behaviour of automatically creating mocks is blocked, as well as for all its "submocks". See sealedmock https://github.com/mariocj89/sealedmock/blob/master/README.md. Don't focus on the implementation, it is ugly, it would be much simpler within *mock.py*.
*Rationale* Inspired by GMock https://github.com/google/googletest/tree/master/googlemock RestrictedMock, SealedMock aims to allow the developer to define a narrow interface to the mock that defines what the mocks allows to be called on. The feature of mocks returning mocks by default is extremely useful but not always desired. Quite often you rely on it only at the time you are writing the test but you want it to be disabled at the time the mock is passed into your code, that is what SealedMock aims to address.
This solution also prevents user errors when mocking incorrect paths or having typos when calling attributes/methods of the mock. We have tried it internally in our company and it gives quite a nicer user experience for many use cases, specially for new users of mock as it helps out when you mock the wrong path.
- Using auto_spec/spec is a possible solution but removes flexibility and is rather painful to write for each of the mocks and submocks being used. - Leaving it outside of the mock.py as it is not interesting enough. I am fine with it :) just proposing it in case you think otherwise. - Make it part of the standard Mock base class. Works for me, but I'd concerned on how can we do it in a backward compatible way. (Say someone is mocking something that has a "sealed" attribute already).
Let me know what you think, happy to open a enhancement in https://bugs.python.org/ and send a PR.