Skip to content

__str__ and __repr__ are ignored for custom iterable objects #17695

Closed
@dmyersturnbull

Description

@dmyersturnbull

I posted a comment on ipython/ipython#2379, but I realized this may be specific to Pandas. I'm using IPython 6.2.0, Python 3.5, Jupyter 4.3.0, and Pandas 0.20.1.

Pandas won't use __str__ or __repr__ (or anything I can find) to display an iterable object that defines __len__

Code Sample, a copy-pastable example if possible

class WithLen:
    z = [1,2,3]
    def __getitem__(self, i): return self.z[i]
    def __str__(self): return "from str"
    def __repr__(self): return "from repr"
    def __len__(self): return len(self.z)

df = pd.DataFrame([
    pd.Series({'test': WithLen()})
])
print(df)  # PROBLEMATIC CASE
print(df['test'].iloc[0])  # prints fine
class WithoutLen:
    z = [1,2,3]
    def __getitem__(self, i): return self.z[i]
    def __str__(self): return "from str"
    def __repr__(self): return "from repr"
    def __len__(self): return len(self.z)

print(pd.DataFrame([
    pd.Series({'test': WithoutLen()})
]))  # prints fine

Problem description

I've implemented __str__ and __repr__ on an iterable class with good reason, and it being iterable shouldn't override that behavior.

Expected Output

I expected and want to see this printed both with and without __len__:

       test
0  from str

Output of pd.show_versions()


INSTALLED VERSIONS
------------------
commit: None
python: 3.5.3.final.0
python-bits: 64
OS: Linux
OS-release: 4.11.6-201.fc25.x86_64
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.utf8
LOCALE: en_US.UTF-8

pandas: 0.20.3
pytest: 3.0.7
pip: 9.0.1
setuptools: 36.5.0
Cython: 0.25.2
numpy: 1.13.1
scipy: 0.19.0
xarray: None
IPython: 6.2.0
sphinx: 1.5.1
patsy: 0.4.1
dateutil: 2.6.1
pytz: 2017.2
blosc: None
bottleneck: 1.2.0
tables: 3.3.0
numexpr: 2.6.2
feather: None
matplotlib: 2.0.2
openpyxl: 2.4.1
xlrd: 1.0.0
xlwt: 1.2.0
xlsxwriter: 0.9.6
lxml: 3.7.3
bs4: 4.5.3
html5lib: 0.999
sqlalchemy: 1.1.6
pymysql: 0.7.11.None
psycopg2: None
jinja2: 2.9.5
s3fs: None
pandas_gbq: None
pandas_datareader: None

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions