2021-03-29

How to write a __repr__ when one of the inputs is a dataframe?

I have a class that takes a pandas dataframe as one of parameters. I've not been very good at adding __repr__ to my code so now I'm trying to go back and add to all the existing codebase. But here I run into the issue:

import pandas as pd

class Foo:
    def __init__(self, data: pd.DataFrame, some_val: str):
        self.data = data
        self.some_val = val

    def __repr__(self):
        return f'Foo(data={self.data}, some_val={self.some_val})'

So in this example if I call repr() on an instance of my class I will get something like:

Out[7]: 'Foo(data=       xcentre   ycentre  ...
n99996     99996  316065.0  295205.0  ...  undef -99.0 
      undef\n99997     99997  316075.0  295205.0  ...  undef -99.0
       undef\n99998     99998  316065.0  295215.0  ...  undef -99.0 
      undef\n99999     99999  316075.0  295215.0  ...  undef -99.0
       undef\n\n[100000 rows x 121 columns], some_val='blabla')'

It is also no surprise I get syntax errors when I try to run eval() on it.

So how should I correctly use __repr__ in this case?



from Recent Questions - Stack Overflow https://ift.tt/3dkEaDg
https://ift.tt/eA8V8J

No comments:

Post a Comment