Skip to content

[BUG] Columns(width=...) raises ZeroDivisionError when the requested width does not fit #4214

Description

@yayong3

Describe the bug

With the default padding (0, 1), width_padding is 1. If the available console width is no greater than width + 1, this calculation returns 0. This will result in an error.
This bug might be related to the following code in rich\columns.py within rich.

def __rich_console__:
       ...
        if self.width is not None:
            column_count = (max_width) // (self.width + width_padding)

__rich_console__ then passes column_count to iter_renderables, which evaluates item_count % column_count and raises ZeroDivisionError.

Reproduction

from io import StringIO

from rich.columns import Columns
from rich.console import Console

console = Console(
    file=StringIO(),
    width=16,
    height=24,
    force_terminal=True,
    color_system=None,
    highlight=False,
)
print("size", console.width, "x", console.height)
console.print(Columns([f"file_{i:02d}.txt" for i in range(8)], width=16))

Observed:

size 16 x 24
Traceback (most recent call last):
  File "/home/test01.py", line 15, in <module>
    console.print(Columns([f"file_{i:02d}.txt" for i in range(8)], width=16))
  File "/home/rich/rich/console.py", line 1731, in print
    extend(render(renderable, render_options))
  File "/home/rich/rich/console.py", line 1339, in render
    for render_output in iter_render:
  File "/home/rich/rich/columns.py", line 145, in __rich_console__
    _renderables = [
                   ^
  File "/home/rich/rich/columns.py", line 115, in iter_renderables
    if item_count % column_count:
       ~~~~~~~~~~~^~~~~~~~~~~~~~
ZeroDivisionError: integer modulo by zero

Same function, zero divisor (optional second case):

console.print(Columns(["alpha", "beta"], width=0, padding=0))
  File "/home/rich/rich/columns.py", line 124, in __rich_console__
    column_count = (max_width) // (self.width + width_padding)
                   ~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ZeroDivisionError: integer division or modulo by zero

Platform

  • Python version: 3.12.3
  • Rich version: 15.0.0 (9d8f9a37)
  • Linux x86_64

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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