[pytest-dev] monkeypatch.setattr versus replace

Florian Schulze florian.schulze at gmx.net
Fri Sep 13 12:50:37 CEST 2013


On 13.09.2013, at 12:33, holger krekel wrote:

> Hi all,
> 
> this was discussed before on IRC, but here is an update and a question.
> currently pytest-trunk implements a convenient new monkeypatch.replace method:
> 
>    # example usage
>    monkeypatch.replace("os.path.abspath", lambda x: "/abc")
> 
> This effectively performs:
> 
>    import os.path
>    monkeypatch.setattr(os.path, "abspath", lambda x: "/abc")
> 
> However, i just wanted to use it and couldn't remember the "replace"
> name and don't find it very telling anymore.  I often do something
> like this::
> 
>    monkeypatch.setattr("os.path.abspath", lambda x: "/abc")
> 
> which currently ends up as an error.  Would it be too awkward to
> just make the latter work and forget about introducing a new "replace"
> method name?  IMO it's rather intuitive to just make setattr accept
> the new signature, although the docstring will need a bit of explaining.

You can easily support both, so I would say go for it and just describe both ways in the docstring.

If you think the old way shouldn't be used, you can also add a deprecation warning to it.

Regards,
Florian Schulze



More information about the Pytest-dev mailing list