WildGunman
WildGunman

Reputation: 393

Overriding subclass methods from imported packages in Python

I'm having trouble figuring out how to override a method in an inherited subclass. I'm using the html2text package, which has a subclass called HTML2Text that does the heavy lifting. I create a new class then as follows:

import html2text
class MyHTML2Text(html2text.HTML2Text):
    def handle_tag(self, tag, attrs, start):
        ...

parser = MyHTML2Text()
parser.handle(hml)

The problem is that when the top level class html2text is imported, it initializes a bunch of subfunctions that are needed for HTML2Text, and they aren't available to the new class, so whenever the new class calls those functions they aren't there.

I know this must be simple, but what is the proper way to override a method in a subclass like this and retain all of the top level initialized stuff in the correct namespace?

Upvotes: 1

Views: 778

Answers (1)

sKwa
sKwa

Reputation: 889

I only want to override the one in that particular subclass.

You can override function explicitly.

#!/usr/bin/env python
# coding: utf-8
import html2text

# store original function for any case
_orig_handle_tag = html2text.HTML2Text.handle_tag


# define a new functiont
def handle_tag(self, tag, attrs, start):
    print('OVERRIDEN')
    print(tag, attrs, start)


# override
html2text.HTML2Text.handle_tag = handle_tag


# test
conv = html2text.HTML2Text()
conv.handle_tag(tag='#python', attrs='some attribute', start=0)

# OUTPUT:
# -------
# OVERRIDEN
# ('#python', 'some attribute', 0)

# restore original function
html2text.HTML2Text.handle_tag = _orig_handle_tag

Upvotes: 2

Related Questions