psf / black

The uncompromising Python code formatter
https://black.readthedocs.io/en/stable/
MIT License
39.16k stars 2.47k forks source link

Support to sort functions/methods by type & name #1936

Closed exhuma closed 3 years ago

exhuma commented 3 years ago

Ensuring that functions/methods are ordered by type is beneficial for code-readability and also to avoid conflicts.

This is very similar to order certain other structures like imports. Ensuring that structures are ordered by a fixed rule ensures that every contributor ends up with the same code during check-in, even if implementing the same solution independently.

For example, if two developers add the same "import", then following the same sorting rules will make that import end up at the same location in the code, and thereby avoid conflicts (or even double imports).

The same can be said for higher-level constructs like functions, methods and classes.

Additionally, you will get an interesting side-effect: It will cause conflicts if two developers implement two different methods with the same name. This would otherwise go unnoticed if the code is not tested/linted properly. Having a conflict in such a situation would be an additional "safety-net".

As black already rewrites the source-code, I thought it could be an interesting candidate to implement this. And maybe it already contains the necessary constructs to facilitate this.

Reordering code can have averse effects though. In rare cases, the ordering of functions/methods may actually be important. But these should remain edge-cases and we already have #fmt: on/off comments to fence off those problematic areas.

This is an aggressive change to the source-code but I see mainly advantages to such a restructuring.

I would see something like the following for Python modules:

Inside classes I could imagine the following:

TylerYep commented 3 years ago

This seems very unlikely to be accepted, since it would likely completely change all existing files formatted by black, and may introduce lots of bugs in existing code.

I think the idea is better implemented as a lint rule, such as the one used in the flake8 plugin here: flake8-class-attributes-order

ichard26 commented 3 years ago

Closing as this idea is too just dangerous to implement. Sometimes the order of function and method definitions matters and this feature throws that out of the water. And we are extremely unlikely to take on another flag for a feature like this.

Points made @TylerYep are also applicable.

Thanks @exhuma for the idea but we won't be implementing this, sorry!