rich_tools icon indicating copy to clipboard operation
rich_tools copied to clipboard

`df_to_table` should not use `Table()` as a default value but an `Optional`

Open romintomasetti opened this issue 1 month ago • 0 comments

Because of https://github.com/avi-perl/rich_tools/blob/7b5b2539f379f9d33270cde81716da53fe805d21/rich_tools/table.py#L11 calling several times in a row df_to_table actually modifies the same table. I guess this is not a desired effect.

It seems that the fix is easy. Just take an Optional[Table] = None instead and initialize the table = Table() accordingly within the function body.

import pandas
import rich.console
import rich_tools

console = rich.console.Console()

df = pandas.DataFrame(data = {
    'column_0' : [0, 1, 2, 3],
    'column_1' : [4, 5, 6, 7],
})

console.print(df)

table = rich_tools.df_to_table(df)

console.print(table)

table = rich_tools.df_to_table(df)

console.print(table)
   column_0  column_1
0         0         4
1         1         5
2         2         6
3         3         7
┏━━━┳━━━━━━━━━━┳━━━━━━━━━━┓
┃   ┃ column_0 ┃ column_1 ┃
┡━━━╇━━━━━━━━━━╇━━━━━━━━━━┩
│ 0 │ 0        │ 4        │
│ 1 │ 1        │ 5        │
│ 2 │ 2        │ 6        │
│ 3 │ 3        │ 7        │
└───┴──────────┴──────────┘
┏━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━┳━━━━━━━━━━┳━━━━━━━━━━┓
┃   ┃ column_0 ┃ column_1 ┃  ┃ column_0 ┃ column_1 ┃
┡━━━╇━━━━━━━━━━╇━━━━━━━━━━╇━━╇━━━━━━━━━━╇━━━━━━━━━━┩
│ 0 │ 0        │ 4        │  │          │          │
│ 1 │ 1        │ 5        │  │          │          │
│ 2 │ 2        │ 6        │  │          │          │
│ 3 │ 3        │ 7        │  │          │          │
└───┴──────────┴──────────┴──┴──────────┴──────────┘

romintomasetti avatar Nov 17 '25 15:11 romintomasetti