Search code examples
pythonvisual-studio-codeformattingautopep8

auto formatting python code to put parameters on same line


I really hate having spread out code, I am looking at a bunch of long code with parameters and arguments that are taking up way to much space.

    def __init__(self,
                 network,
                 value_coef, 
                 entropy_coef, 
                 lr=None,
                 eps=None,
                 max_grad_norm=None,
                 conv=False):

Seems the guy who wrote it forced a 50 character line limit, I whole heartedly disagree. I would much rather it looked like this.

    def __init__(self, network, value_coef, entropy_coef, lr=None, eps=None, max_grad_norm=None, conv=False):

There is also more nonsense like this which I would like to get rid of.

        if self.conv:
            grid_obs = rollouts.grid_obs[:-1]\
                .view(-1, *rollouts.grid_obs.size()[2:])
            dest_obs = rollouts.dest_obs[:-1]\
                .view(-1, *rollouts.dest_obs.size()[2:])
            obs = (grid_obs, dest_obs)

I am using VS code for the python and am an ex Intellij user and am missing all the built in code formatting code tools. Any one got any tips? I have been looking at autopep8 but it seems they are missing that functionality.


Solution

  • First, that's not 50 chars limit but 79 (as per pep8 conventions) and the way you would like to have it wouldn't be pep8 compliant as it's over 100 columns.

    So, for the first snippet you can have it the way you don't like it (which is the correct way) or let your formatter know that you want the line-length to be over 79 columns.

    For the second snippet you can remove the escape character \ and let the formatter do its job. I don't think it's 'nonsense' as you call it, but feel free to format it differently.

    Autopep8 or Black both work very well and they are not missing any functionality.

    Provided you installed one or the other, you have to add the proper key/value pair to your settings.json:

    "python.formatting.provider": "autopep8" // (or "black")
    

    If you use autopep8, for example, you can specify the line length you want (150 in your case) by adding this to your settings.json file:

    "python.formatting.autopep8Args": [
        "--line-length=150"
    ]
    

    The same goes for black. In that case the value would be:

    "python.formatting.blackArgs": [
        "--line-length=150"
    ]
    

    Formatting with that parameter will wrap your code to that amount.

    You can format code with alt+shift+f (on a Mac) or right click on the editor and "Format Document".