Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I override a function of a python library?

I am using a python library where I need to override one of the functions. Let's call this module.py:

def dump(nodes, args = 'bleh' ):
  ...validation checks
  for node in nodes:
    print(node, someother_args)

def print_node(node, someother_args):
  ...prints in some way i don't want

Now, I am using this dump method and I want to override the print_node function with my own print_node method because I want to print it in different way. What is the best way to do that?

like image 288
paris_serviola Avatar asked Oct 19 '22 08:10

paris_serviola


1 Answers

You can create a class by yourself that inherits from intended module, and override the function in any way you want. Then you can use your object instead of module.py.

class my_class(module):
    def __init__(self, *args, **kwargs):
        super(my_class, self).__init__(*args, **kwargs)
    def dump(self):
        # do stuff

As you mentioned in comment if your module is contain a bunch of functions you better to define the new function in your current module. Then you can assign it to that function name.

As @Joran Beasley also mentioned, you can do something like following

import my_file
my_file.dump = my_local_dump_fn
like image 117
Mazdak Avatar answered Oct 21 '22 06:10

Mazdak