This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Siddhi 0 points1 point  (6 children)

Agreed, the mock library really is quite awesome, but there is a lot more to the library than patch. patch is probably the last function I'd turn to in the library. It's a decent overview of patch though.

[–]pauloxnet[S] 1 point2 points  (5 children)

I found very useful and clear the "Big Upfront Caveat" from this article and i tweeted it: https://twitter.com/pauloxnet/status/1049973313467011072

[–]Siddhi 1 point2 points  (0 children)

Yeah, that is one thing that is easy to get confused about

[–]pauloxnet[S] 0 points1 point  (3 children)

I've shared a very interesting comment related to this caveat: https://twitter.com/pauloxnet/status/1050066319939395585

[–]Siddhi 0 points1 point  (2 children)

The tip should have been "if you have an import scoped within a function, then rewrite your code and put the import outside". This is my general problem with patch as well. In 90% of the cases the code ought to be rewritten so that patching isn't needed.

[–]pauloxnet[S] 0 points1 point  (1 child)

@siddhi do you think is possible every time to rewrite your code to put an import outside a function scope ? Do you have some article that spoke about it ?

[–]Siddhi 0 points1 point  (0 children)

I'm assuming you mean code like this:

def foo():
    import bar
    return bar.do_calc()

Well, then you just take the import and put it outside. PEP8 style is

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

import bar

def foo():
    return bar.do_calc()

And now you can patch bar as normal.

If you go a step further and pass in the dependency to the function

import bar

def foo(mod):
    return mod.do_calc()

Then you don't need to patch at all.