Search code examples
pythonpycharmword-wrap

PyCharm reformat code does not wrap line to specified length


When I highlight a section of python code in PyCharm 2020.3 Community Edition and attempt a reformat code operation, the reformatted code does not respect the 80 character limit I (believe that I) specified in the settings.

What am I doing wrong?

My settings are as shown below:

enter image description here

For example, I would like the 86 character line:

        normalized_stop_band_edge: float = prms['stop_band_edge_in_hz'] * sam_int_in_s

to be reformatted to, e.g.,:

        normalized_stop_band_edge: float = prms['stop_band_edge_in_hz'] * \
                                           sam_int_in_s

Solution

  • The line wrapping is language specific. In the question a screenshot of the general IDE setting is shown, but if working with a Python file the general editor setting is superseded by the language specific setting.

    For the example code in the question to wrap for the line length limit using Reformat Code (Ctrl + Alt + L) 2 settings must be configured: At File > Settings > Editor > Code Style > Python > Wrapping and Braces.

    1. Hard wrap at (80).
    2. Ensure right margin is not exceeded

    enter image description here

    But this is still not enough. It has to be considered the example in the question has 2 levels of indentation (8 whitespaces, or 2 tabs). This will require running Reformat Code (Ctrl + Alt + L) twice, and that the example line be in a scope that has 2 levels of indentation. So for example:

    class MyClass:
        @staticmethod
        def my_func():
    
            normalized_stop_band_edge: float = prms['stop_band_edge_in_hz'] * sam_int_in_s
    

    Initially:

    enter image description here

    After pressing Ctrl + Alt + L once:

    enter image description here

    After pressing Ctrl + Alt + L twice:

    enter image description here