Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CI: Added isort import check for the code on pull-request #4242

Merged
merged 7 commits into from
Nov 13, 2020
Merged

CI: Added isort import check for the code on pull-request #4242

merged 7 commits into from
Nov 13, 2020

Conversation

nathanpainchaud
Copy link
Contributor

What does this PR do?

Fixes #4241

Before submitting

  • Was this discussed/approved via a Github issue? (no need for typos and docs improvements)
  • Did you read the contributor guideline, Pull Request section?
  • Did you make sure your PR does only one thing, instead of bundling different changes together? Otherwise, we ask you to create a separate PR for every change.
  • Did you make sure to update the documentation with your changes?
  • Did you write any new necessary tests?
  • Did you verify new and existing tests pass locally with your changes?
  • If you made a notable change (that affects users), did you update the CHANGELOG?

PR review

Anyone in the community is free to review the PR once the tests have passed.
If we didn't discuss your PR in Github issues there's a high chance it will not be merged.

Did you have fun?

Make sure you had fun coding 🙃

@mergify mergify bot requested a review from a team October 19, 2020 20:38
@Borda Borda added the feature Is an improvement or enhancement label Oct 19, 2020
setup.cfg Show resolved Hide resolved
@mergify mergify bot requested a review from a team October 19, 2020 21:46
@edenlightning edenlightning added this to the 1.0.3 milestone Oct 19, 2020

[tool.isort]
known_first_party = ["pytorch_lightning","tests","pl_examples"]
profile = "black"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Borda would we want use black style for sorting or other? There is also pycharm style https://pycqa.github.io/isort/docs/configuration/profiles/

Hi @nathanpainchaud which profile do you think is suitable for lightning which follows pep8 for code formatting?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we get some examples?
for me split to three sections: build-in, third-party and locals

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is with black profile using command as this PR

import collections
import copy
import inspect
import os
import re
import tempfile
from abc import ABC
from argparse import Namespace
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union

import torch
from torch import ScriptModule, Tensor
from torch.nn import Module
from torch.optim.optimizer import Optimizer

from pytorch_lightning import _logger as log
from pytorch_lightning.core.grads import GradInformation
from pytorch_lightning.core.hooks import CheckpointHooks, DataHooks, ModelHooks
from pytorch_lightning.core.memory import ModelSummary
from pytorch_lightning.core.saving import ALLOWED_CONFIG_TYPES, PRIMITIVE_TYPES, ModelIO
from pytorch_lightning.core.step_result import Result
from pytorch_lightning.utilities import rank_zero_warn
from pytorch_lightning.utilities.device_dtype_mixin import DeviceDtypeModuleMixin
from pytorch_lightning.utilities.exceptions import MisconfigurationException
from pytorch_lightning.utilities.parsing import AttributeDict, collect_init_args, get_init_args
from pytorch_lightning.utilities.xla_device_utils import XLADeviceUtils

with pycharm profile

import collections
import copy
import inspect
import os
import re
import tempfile
from abc import ABC
from argparse import Namespace
from typing import (
    Any,
    Callable,
    Dict,
    List,
    Optional,
    Sequence,
    Tuple,
    Union
)

import torch
from torch import (
    ScriptModule,
    Tensor
)
from torch.nn import Module
from torch.optim.optimizer import Optimizer

from pytorch_lightning import _logger as log
from pytorch_lightning.core.grads import GradInformation
from pytorch_lightning.core.hooks import (
    CheckpointHooks,
    DataHooks,
    ModelHooks
)
from pytorch_lightning.core.memory import ModelSummary
from pytorch_lightning.core.saving import (
    ALLOWED_CONFIG_TYPES,
    PRIMITIVE_TYPES,
    ModelIO
)
from pytorch_lightning.core.step_result import Result
from pytorch_lightning.utilities import rank_zero_warn
from pytorch_lightning.utilities.device_dtype_mixin import DeviceDtypeModuleMixin
from pytorch_lightning.utilities.exceptions import MisconfigurationException
from pytorch_lightning.utilities.parsing import (
    AttributeDict,
    collect_init_args,
    get_init_args
)
from pytorch_lightning.utilities.xla_device_utils import XLADeviceUtils

with google profile

from abc import ABC
from argparse import Namespace
import collections
import copy
import inspect
import os
import re
import tempfile
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union

import torch
from torch import ScriptModule
from torch import Tensor
from torch.nn import Module
from torch.optim.optimizer import Optimizer

from pytorch_lightning import _logger as log
from pytorch_lightning.core.grads import GradInformation
from pytorch_lightning.core.hooks import CheckpointHooks
from pytorch_lightning.core.hooks import DataHooks
from pytorch_lightning.core.hooks import ModelHooks
from pytorch_lightning.core.memory import ModelSummary
from pytorch_lightning.core.saving import ALLOWED_CONFIG_TYPES
from pytorch_lightning.core.saving import ModelIO
from pytorch_lightning.core.saving import PRIMITIVE_TYPES
from pytorch_lightning.core.step_result import Result
from pytorch_lightning.utilities import rank_zero_warn
from pytorch_lightning.utilities.device_dtype_mixin import DeviceDtypeModuleMixin
from pytorch_lightning.utilities.exceptions import MisconfigurationException
from pytorch_lightning.utilities.parsing import AttributeDict
from pytorch_lightning.utilities.parsing import collect_init_args
from pytorch_lightning.utilities.parsing import get_init_args
from pytorch_lightning.utilities.xla_device_utils import XLADeviceUtils

no profile

import collections
import copy
import inspect
import os
import re
import tempfile
from abc import ABC
from argparse import Namespace
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union

import torch
from torch import ScriptModule, Tensor
from torch.nn import Module
from torch.optim.optimizer import Optimizer

from pytorch_lightning import _logger as log
from pytorch_lightning.core.grads import GradInformation
from pytorch_lightning.core.hooks import CheckpointHooks, DataHooks, ModelHooks
from pytorch_lightning.core.memory import ModelSummary
from pytorch_lightning.core.saving import ALLOWED_CONFIG_TYPES, PRIMITIVE_TYPES, ModelIO
from pytorch_lightning.core.step_result import Result
from pytorch_lightning.utilities import rank_zero_warn
from pytorch_lightning.utilities.device_dtype_mixin import DeviceDtypeModuleMixin
from pytorch_lightning.utilities.exceptions import MisconfigurationException
from pytorch_lightning.utilities.parsing import AttributeDict, collect_init_args, get_init_args
from pytorch_lightning.utilities.xla_device_utils import XLADeviceUtils

All of them split built-in, third-party, locals

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ydcjeff already gave a good explanation. What I can add to this is that since PL has already decided to use black for formatting the code, I would heavily suggest using the black profile. Otherwise, we might fall into a "deadlock" between checks, where isort and black suggest conflicting changes (speaking from experience there 😛) Using the black profile guarantees that both tools won't conflict with each other.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think PL isn't using black
cc: @Borda

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not back for codebase just for formating imports

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, my bad! I saw the pre-commit hook for black and I thought it was already in use. In that case, it's a bit up to personal preference, and what we want to prioritize.

I like the black format myself, but for a community project like PL I think a profile with single line imports (like google and open_stack) might prevent some conflicts in the imports.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 from me on black with consistent string formatting too. makes my OCD go crazy when i see some variables with single quotes and others with double quotes in the same file :)

@mergify mergify bot requested a review from a team October 20, 2020 07:07
- name: Install isort
run: pip install isort==5.6.4
- name: Run isort
run: isort --settings-path=./pyproject.toml --check-only .
Copy link
Contributor

@akihironitta akihironitta Oct 20, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a strong opinion, but how about adding --diff option?

 -df, --diff           Prints a diff of all the changes isort would make to a
                        file, instead of changing it in place

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @nathanpainchaud, --diff would be nice to see actually.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The --check-only option already lists the file that would be changed, without changing them in-place. From what I understand, --diff would print all the changes, even inside each file. I've got no problem adding it, I just want to make sure it wouldn't be considered too noisy in the end.

Copy link
Contributor

@tchaton tchaton left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks a lot ! Great addition to Pytorch Lightning. Would you mind adding it in pre-commit and resolving unit-tests ?

- name: Install isort
run: pip install isort==5.6.4
- name: Run isort
run: isort --settings-path=./pyproject.toml --check-only .
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @nathanpainchaud, --diff would be nice to see actually.

@@ -7,6 +7,21 @@ on: # Trigger the workflow on push or pull request, but only for the master bra
branches: [master]

jobs:
isort:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add isort to pre-commit too. Here is an example: https://github.com/PyCQA/isort/blob/develop/.pre-commit-config.yaml

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I already did actually 😉 But I asked @Borda about it, and he wanted to keep the pre-commit hook for a different PR. When you're ready for it, you can just ping me though, because I already have it locally!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes as with accepting the CI check we need to format the codebase accordingly...

@nathanpainchaud
Copy link
Contributor Author

nathanpainchaud commented Oct 20, 2020

Thanks a lot ! Great addition to Pytorch Lightning. Would you mind adding it in pre-commit and resolving unit-tests ?

@tchaton when you mean resolving the unit-tests, do you mean applying the changes isort suggests? Because when I ran the pre-commit manually, a big part of the repo would be affected (160 files). Would we want to do it all in one PR, or run isort on the files as they are updated?

@mergify
Copy link
Contributor

mergify bot commented Oct 20, 2020

This pull request is now in conflict... :(

@nathanpainchaud
Copy link
Contributor Author

I added the isort pre-commit hook to this PR, and applied the changes as well.

I didn't know of a way to give the authorship of the formatting commit to an automatic task rather than myself. If you would prefer it that way, I would be grateful if you could point me to indications on how to do so and I'll reapply the formatting.

@codecov
Copy link

codecov bot commented Oct 20, 2020

Codecov Report

Merging #4242 (f5f9d1c) into master (baa8558) will increase coverage by 0%.
The diff coverage is n/a.

@@          Coverage Diff           @@
##           master   #4242   +/-   ##
======================================
  Coverage      93%     93%           
======================================
  Files         117     117           
  Lines        8914    8914           
======================================
+ Hits         8280    8283    +3     
+ Misses        634     631    -3     

@nathanpainchaud nathanpainchaud requested review from tchaton and removed request for a team October 20, 2020 18:40
@mergify mergify bot requested a review from a team October 20, 2020 18:41
@mergify
Copy link
Contributor

mergify bot commented Oct 21, 2020

This pull request is now in conflict... :(

1 similar comment
@mergify
Copy link
Contributor

mergify bot commented Oct 21, 2020

This pull request is now in conflict... :(

- name: Install isort
run: pip install isort==5.6.4
- name: Run isort
run: isort --settings-path=./pyproject.toml --diff .
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you keep --check option to obtain UNIX exit status? Without --check, it always exits with 0, and it means that isort check always passes on GitHub Actions no matter what the source code is. I have checked the behaviour at https://github.com/akihironitta/ci-example/runs/1305737153.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. I assumed that --diff also caused returned an error code, since it doesn't modify the files in-place (much like --check-only in this sense). I didn't think to test it out. I've added back the --check-only flag.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the swift action!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isort --help now has the description of the exit status of --check on the main branch! PyCQA/isort#1590

Checks the file for unsorted / unformatted imports and 
prints them to the command line without modifying the file. 
Returns 0 when nothing would change and returns 1 when 
the file would be reformatted.

@mergify
Copy link
Contributor

mergify bot commented Oct 26, 2020

This pull request is now in conflict... :(

@nathanpainchaud
Copy link
Contributor Author

I saw that issue #4241 for this was closed, but that a PR with the same goal was merged in bolts. @Borda, @ananthsub, @tchaton, @akihironitta any updates on what you want me to do with this PR to get this merged?

@nathanpainchaud
Copy link
Contributor Author

With the new configuration, isort only applies on root-level (i.e. setup.py), docs and benchmarks right now. That's also the only things the CI will check. However, the pre-commit hook is active, and every new file committed (across the whole repo, not just within the subdirectories mentioned) will be checked locally for sorted imports.

Eventually, we'll have to delete some glob expressions from the skipped files (https://github.com/nathanpainchaud/pytorch-lightning/blob/ci/4241_import_sort/pyproject.toml#L25-L29) to turn on the CI checks for them.

@Borda
Copy link
Member

Borda commented Nov 10, 2020

Eventually, we'll have to delete some glob expressions from the skipped files (https://github.com/nathanpainchaud/pytorch-lightning/blob/ci/4241_import_sort/pyproject.toml#L25-L29) to turn on the CI checks for them.

that could be a solution for us, step-by-step reduce the skip pattern, similar as we have type check
https://github.com/PyTorchLightning/pytorch-lightning/blob/master/.pyrightconfig.json

@nathanpainchaud
Copy link
Contributor Author

step-by-step reduce the skip pattern

I'm glad that seems to be doing the trick for you! Given how isort functions, I don't even know (as of now) of any other way we could do it incrementally 😅

However, seeing as the pre-commit is still active for all files, I don't think it will be too long before most of the files' imports are sorted 😉

@Borda
Copy link
Member

Borda commented Nov 10, 2020

step-by-step reduce the skip pattern

I'm glad that seems to be doing the trick for you! Given how isort functions, I don't even know (as of now) of any other way we could do it incrementally 😅

I have not checked it yet, just a proposal to try

However, seeing as the pre-commit is still active for all files, I don't think it will be too long before most of the files' imports are sorted 😉

yes, but not everyone is using pre-commit... for this peace by peace changes you temporarily disable it and apply isort just for some files, right?

so let's change this PR such that it will introduce isort in pre-commit and in CI with ignoring all codebase, the create several smaller PRs wich would fix a few files and remove some patter from CI
cc: @PyTorchLightning/core-contributors

@nathanpainchaud
Copy link
Contributor Author

for this peace by peace changes you temporarily disable it and apply isort just for some files, right?

Yes. Right now, I just applied isort to root-level (i.e. setup.py), docs and benchmarks to give a preview of the format used.

so let's change this PR such that it will introduce isort in pre-commit and in CI with ignoring all codebase, the create several smaller PRs wich would fix a few files and remove some patter from CI

What you're proposing is what the PR is doing in its current state (since the changes I made earlier today). The only files currently affected are the exceptions mentioned above. Tests, examples and the library itself are currently excluded from CI checks.

Copy link
Member

@Borda Borda left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like this initial step :]

@edenlightning edenlightning modified the milestones: 1.0.x, 1.0.7 Nov 10, 2020
@Borda Borda modified the milestones: 1.0.7, 1.0.x Nov 11, 2020
Copy link
Contributor

@rohitgr7 rohitgr7 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Just a comment.

@edenlightning edenlightning modified the milestones: 1.0.x, 1.0.7 Nov 13, 2020
@Borda Borda modified the milestones: 1.0.7, 1.0.x Nov 13, 2020
@Borda Borda added the ready PRs ready to be merged label Nov 13, 2020
@Borda Borda merged commit 2d78d9b into Lightning-AI:master Nov 13, 2020
@nathanpainchaud nathanpainchaud deleted the ci/4241_import_sort branch November 14, 2020 01:15
tchaton added a commit that referenced this pull request Nov 17, 2020
* added isort CI job and updated isort config

* changed CI check output from files to full diff

* added isort pre-commit hook

* Added missing first party and restricted files affected by isort

* Applied isort to root-level, docs and benchmarks

* Apply suggestions from code review

Co-authored-by: Nathan Painchaud <nathanpainchaud@gmail.com>
Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com>
Co-authored-by: chaton <thomas@grid.ai>
rohitgr7 pushed a commit that referenced this pull request Nov 21, 2020
* added isort CI job and updated isort config

* changed CI check output from files to full diff

* added isort pre-commit hook

* Added missing first party and restricted files affected by isort

* Applied isort to root-level, docs and benchmarks

* Apply suggestions from code review

Co-authored-by: Nathan Painchaud <nathanpainchaud@gmail.com>
Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com>
Co-authored-by: chaton <thomas@grid.ai>
@akihironitta akihironitta mentioned this pull request Nov 22, 2020
30 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature Is an improvement or enhancement ready PRs ready to be merged
Projects
None yet
Development

Successfully merging this pull request may close these issues.

add CI check for valid import formatting
8 participants