How to replace an instance method?

Ralf M. Ralf_M at t-online.de
Sat Sep 17 17:21:08 EDT 2022


Am 17.09.2022 um 00:35 schrieb Dan Stromberg:
> 
> 
> On Fri, Sep 16, 2022 at 2:06 PM Ralf M. <Ralf_M at t-online.de 
> <mailto:Ralf_M at t-online.de>> wrote:
> 
>     I would like to replace a method of an instance, but don't know how to
>     do it properly.
> 
> 
> You appear to have a good answer, but...  are you sure this is a good idea?

It's definitely a dirty hack.

> It'll probably be confusing to future maintainers of this code, and I 
> doubt static analyzers will like it either.

I agree that I will have to add sufficient comments for the future
maintainer, should there ever be one (and even for me to still
understand it next year). I don't use static analyzers.

> I'm not the biggest fan of inheritance you'll ever meet, but maybe this 
> is a good place for it?

Using a derived version of the class in question to overwrite the
method was my first idea, however I don't instantiate the class in
question myself, it is instantiated during the initialisation of
another class, so I would at least have to derive a modified version of
that as well. And that code is rather complex, with metaclasses and
custom decorators, and I feel uncomfortable messing with that, while
the method I intend to change is quite simple and straightforward.

In case anybody is interested what I'm trying to achieve:

It's simple in pandas to read an excel file into a dataframe, but only
the cell value is read. Sometimes I need more / other information, e.g.
some formatting or the hyperlink in a cell. Reopening the file with
openpyxl and getting the info is possible, but cumbersome.
Looking into the pandas code for reading excel files (which uses
openpyxl internally) I noticed a method (of an internal pandas class)
that extracts the value from an openpyxl cell. This method is rather
simple and seems the ideal spot to change to get what I want.

My idea is to instantiate pandas.ExcelFile (official pandas API), get
the reader instance (an attribute of the ExcelFile object) and modify
the method of the reader instance.

The fact that the method I change and the ExcelFile attribute containing
the reader are both private (start with _) doesn't make it any better,
but I'm desperate enough to be willing to adapt my code to every major
pandas release, if necessary.

Ralf M.


More information about the Python-list mailing list