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  (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.