PyCQA / isort

A Python utility / library to sort imports.
https://pycqa.github.io/isort/
MIT License
6.49k stars 580 forks source link

New feature: isort should move module-level-dunders to the correct place #1980

Open clavedeluna opened 2 years ago

clavedeluna commented 2 years ago

I can see in a related issue #711 dunders were at least prevented from moving. However, according to PEP8, dunders should come after future imports but before the other import block.

This is correct according to PEP8

from __future__ import barry_as_FLUFL

__all__ = ["barry_as_FLUFL"]
__version__ = '0.1'
__author__ = 'someone'

import os
import sys

This is incorrect


from __future__ import barry_as_FLUFL

import os 
import sys

__all__ = ["barry_as_FLUFL"]
__version__ = '0.1'
__author__ = 'someone'

But currently isort does not move the dunders. I propose this is implemented to correctly align with PEP8. Related pylint issue https://github.com/PyCQA/pylint/issues/5471

kaparoo commented 1 year ago

Hi! Is there any further progress?

clavedeluna commented 1 year ago

In the course of working on this feature I've encountered an example which would defy the PEP8 instructions.

This example is actually within isort:

from importlib import metadata

__version__ = metadata.version("isort")

PEP8 says to move version up above the import, but it in fact depends on the import! I'm not sure what the guidance would be here, I can do some research, but I would expect not to change anything in this case. It would be a bit difficult to detect correctly though.

clavedeluna commented 1 year ago

Given the resolution of https://github.com/python/peps/issues/2971#issuecomment-1387178523 I think there are two options here:

  1. If a dunder assignment relies on an import, that dunder assignment should be placed right after that import, separate from the other module dunders and potentially breaking up the import statements.
  2. Do not touch the code at all if any dunder assignment relies on an import line. This would at least not break anything and keep consistency.

I like 2 best for simplicity, but either option is going to require detecting if a dunder assignment relies on an import statement, which may be challenging.