How to add, delete and edit some lines inside the functions without completely rewriting in Python?

Viewed 110

I want to make minor changes (~10 lines, including editing and deleting the existing lines, and adding new lines) in the middle of a long function (~200 lines) offered by an installed pypi package.

For example:

def func(*args, **kwargs)
    ... # other lines remain unchanged
    some lines which I want to edit
    ... # other lines remain unchanged

AFAIK, the decorators only add code in the beginning/end of a function, and inheritance is a basic solution but it may need a lot of unnecessary copying since I only want to change a relativaly small amount of code. I cannot directly editing the package either since the package is read-only for me and IMHO it is an inelegant solution.

So is there any simple and elegant solutions (i.e., implemented with small amount of code and good readability) to achieve this goal?

2 Answers

Indeed changing the contents of installed packages is a no go. You cannot change a portion of a function's code dynamically as I understand from you question. Since this is a function, you could redefine it in your own project and assign it to the package's function after importing it. e.g.

# in your mylib.py
def your_slightly_modified_func(*args, **kwargs):
    # your awesome implementation
    pass


# in your usage location
import mylib
import lib_from_pypi

lib_from_pypi.func = mylib.your_slightly_modified_func

Now when you call the function from the installed package, it is going to use your own version of the function.

In short, no. There is no "pretty" solution for this. Options are:

  • Copy-paste the whole function into an own file. Monkey-patch it onto the source module when your "correction" is imported.
  • Import the function and patch the bytecode somehow (however this is likely to work in one python release only)
  • If it is an open-source module, fork it and make a custom build (this is arguably the cleanest solution).
  • (Edit): ... or send a pull-request to the original project ;-)

In any case, document it well.

Related