Skip to content

Formatting Tabular Data with black - Special Formatting Rules for Code Blocks #3341

@randolf-scholz

Description

@randolf-scholz

Is your feature request related to a problem? Please describe.

Sometimes I find myself needing small tables of data for configuration, for example a table containing units and upper and lower bounds for some pandas.DataFrame.

An example:

metadata = {  # formatted with black
    "Glucose": ["g/L", 0, 20],
    "DOT": ["%", 0, 100],
    "Volume": ["mL", 0, None],
}

I am deeply convinced that for this kind of manual data entries in source code, fixed width format is vastly superior in terms of readability in the vast majority of cases, especially if the tables get just a bit larger. (There are exceptions of course, such as when the size of entries differs a lot from row to row.)

Describe the solution you'd like

I think it would be nice if black allowed to turn on/off specific formatting rules for code blocks which ensures vertical alignment inside (potentially nested) literal lists/tuples/dictionaries. This form of formatting is used by literally all libraries that work with tables (pandas, numpy, etc.)

# fmt: on[table]
metadata = {
    "Glucose": ["g/L", 0, 20  ],
    "DOT":     ["%",   0, 100 ],
    "Volume":  ["mL",  0, None],
}
# fmt: off[table]

Describe alternatives you've considered

Currently, I am using # fmt: off and # fmt: on and manually format the tables, which is tedious.

Metadata

Metadata

Assignees

No one assigned

    Labels

    S: needs discussionNeeds further hashing out before ready for implementation (on desirability, feasibility, etc.)T: enhancementNew feature or requestT: styleWhat do we want Blackened code to look like?
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions