0

I am in search for the right approach to monkey patch any function in a python module from within my app without modifying the modules package itself.

The background of my question is that my app is using Elasticsearch 2. ES 2 does not accept indexing of documents where fieldnames contain periods. Since my app uses pyes in multiple locations, I'd like to globally patch the indexing method and make sure that any period characters will be turned to underscore characters.

Jabb
  • 3,414
  • 8
  • 35
  • 58

1 Answers1

0

One of the best solution is using wrapper. Create a module and use the same name you want to patch, then in your sources use from mymodule import ES.

In this way, all requests comes to your module and you can decide to run the original or modify it.

another solution is patch in each step:

from pyes import ES
real_create_index = ES.indices.create_index
def create_index(self, idx_name):
    # do what you need
    real_create_index(self, idx_name)
ES.indices.create_index = create_index

from now on, whoever call conn.indices.create_index it will redirect to your code.

Martin Valgur
  • 5,793
  • 1
  • 33
  • 45
Ali Nikneshan
  • 3,500
  • 27
  • 39