[TIP] removing attributes and dictionary keys using mock.patch

Michael Foord michael at voidspace.org.uk
Mon Dec 8 03:42:03 PST 2014

On 08/12/14 11:39, Chris Withers wrote:
> On 07/12/2014 21:51, Michael Foord wrote:
>>>> So, removing an attribute is not possible in the *general* case. In 
>>>> the specific case of it being an instance attribute you can remove 
>>>> it from the object dictionary.
>>> Yeah, my take on it is "anything where delattr works"...
>> But how will you know?
> Well, if it doesn't work, I'd expect it to blow up with an exception 
> or not do anything. Either way, I'm one of those people who believes 
> in writing and verifying a test fails first, in the way I expect, so 
> should be okay ;-)

Yeah, on reflection I think that's alright. If people use it in a way 
that can't work that's their problem.

>>> A whole separate set of decorators/context managers/etc seems like 
>>> overkill, so I hope that's not your preference ;-)
>> A marker object would be better. Like:
>> DELETE = sentinel.DELETE
>> with patch('foo.bar', attribute=DELETE):
>>     ...
> Glad we're in agreement!

Yep, it's a nice api. I hadn't thought of it, so kudos - thanks.

>> Please create on issue on bugs.python.org, preferably with patch, 
>> tests and docs :-)
> Hg branch good? I do have commits rights ;-)
> How would this get into the Mock release for Python 2?
> What version of Python 3 would it land in? 3.5?

Yep, base it on Python 3.5. Let me have a look at the patch, and then 
you can just commit.

I'm afraid I'm badly behind with a mock release for Python 2. There are 
a lot of features that need backporting. I'm hoping to put some time 
into it over christmas. Help very welcomed on that front.

All the best,


> cheers,
> Chris

More information about the testing-in-python mailing list