Feedback wanted on pyorder, a Python definition-ordering linter

Hi everyone,

I’ve been working on pyorder, a linter that orders function and class definitions in Python files. It uses the AST to find definitions and applies rules such as callers before callees, functions before classes at module level, and constructors and special methods earlier in class bodies. It can show a diff or reorder files with pyorder check --fix.

I’d appreciate feedback, especially on a few design questions:

  • Do these ordering rules seem useful and predictable?
  • How should caller-before-callee behave when there are cycles or definition-time dependencies?
  • Would you trust an auto-fix that moves definitions while preserving their source text?
  • Are there common patterns or edge cases that this approach might handle poorly?

It requires Python 3.12+. The README has examples and the full rule list: pyorder on GitHub.

Thanks for taking a look!

Any reason this is a standalone tool rather than a custom rule in an existing linter/formatter? esp since it’s written in Python.

How should caller-before-callee behave when there are cycles or definition-time dependencies?

Falling back to source order seems reasonable here

Would you trust an auto-fix that moves definitions while preserving their source text?

I would trust it more than one that doesn’t preserve the source text :stuck_out_tongue:

I could see this being useful. Function ordering can get really messy.

I usually put Classes at the top, and dataclasses at the very top. I cannot see myself changing that habit, even for the sake of a useful linter.
It’s not obvious to me whether callers belong above or below callees. But being predictable there is a nice feature.
When there is a cycle, it would make sense to me to treat that cycle as a block, sort within that cycle following the normal rules (alphabetically if there are no other determining factors), and determine the position of the block by looking at the top element of the block.
I think there are significant problems using this in the way I usually use a linter (as something that is automatically applied, and the passing of which is required for integration in git). Git diffs would regularly get very complicated, whenever a function is renamed, or if the caller-callee relations change.

I use ruff as my python linter and formatter and it doesnt do anything in this direction and it does not have a plugin system as far as I know and I did not like how ssort works because I wanter topdown or callers first ordering.

Currently cycles are handled by condensation and get simply the same rank and are ordered accordingly by the following sort keys if there is a tie.

The --fix option is actually just intended to reorder the definitions between themselves and you’re supposed to review after, its just a convenience flag to fix the expected order because obviously there is no way to guarantee correct code after reordering

Thanks, these are helpful points!

Classes/dataclasses first is a reasonable preference. Currently, customization requires a plugin, so making preferences like that easier to configure is worth considering.

Your cycle-block suggestion makes sense too. Pyorder currently gives cycle members the same graph rank and applies the remaining sorting rules, but it doesn’t guarantee they stay together as a block.

The Git diff concern is a real trade-off. Renaming a function or changing its references can move otherwise unchanged code, making reviews and merges harder. Preserving source text doesn’t prevent that churn. I can see why you’d prefer using it occasionally rather than enforcing it on every commit.

And I agree: caller-before-callee is a convention, not an objectively correct order—the goal is predictability and if caller before callees is not a wanted goal the ssort is probably the better tool for this anyway

Really? I’d consider this to be backwards, unless I’m misunderstanding you. I generally expect to define before use, for example:

def auth():
    """Authenticate with Google. Must be done prior to any other commands."""
    ...

def list():
    """List calendars available to your account"""
    auth()
    ...

def show(calendar=DEFAULT_CALENDAR, days=3, tz=False):
    auth()
    ...

So whenever you’re looking at a symbol, the first instance of that symbol should usually be the definition of it. It’s generally easier to read that way.

I read the README and I would not use this. I think the goal of defining a deterministic rule-based order of definitions is wrong. It is based on the premise that a programmer’s ordering is always meaningless. Therefore, fine to erase it. To me, alphabetizing is especially wrong in this context.

Linters like this exist for some other languages. For example, Rust’s clippy has module-item-order-groupings and module-items-ordered-within-groupings, which provides enough flexibility in configuration the order of items in modules/enums/traits/impls for most cases.

I don’t really care for auto-fixing myself, as a lint in my IDE would be enough. You say you’re not supporting linting suppression directives, which is unfortunate IMO, because I would definitely avoid any blanket re-ordering rules for the following levels:

  • Methods in classes (the method order is very subjective)
  • Enums (enum member order has observable runtime effects, such as when iterating, or when declaring values with enum.auto(), and it’s not syntactically possible to distinguish between an enum and a standard class). There’s the @enum.member decorator which can be applied to function definitions to turn them into a member, which will trigger your linter.

For me it is the opposite, I wanna see the most important functionality first and helpers after, but your order is also valid, all depends on preference. For callees first, there is already a great tool called ssort

Also a valid point, for me it would be not a preferable design choice that the order in which functions and classes are defined is relevant for their correctness, but thats up to the programmer oc and then you definitely should not use it. Regarding the alphabetizing: It is just the last sorting key that only decides order if all other keys before are a tie.

Yes no suppression comments are unfortunate, however there are plugins. IDE makes sense, but I was aiming for a pre commit hook when I wrote it, I am debating if I should also make it a VS Code plugin.

It’s not just about whether it’s relevant to the runnability of the program. It’s about whether the order of functions is a design choice by the programmer (eg grouping related helpers together), or if it’s an irrelevant thing that you can arbitrarily destroy.

You can easily write a program that goes through your Python code and replaces all variable names with unique names guaranteed not to cause confusion. But I think most of us would rightly push back, because we know that variable names are deliberate choices that should be maintained. [1] The entire premise of pyorder is that the order of functions is not a design choice and therefore can be thrown away. I disagree, as does Terry.


  1. There is a use-case for minification, of course, but at that point, it’s not source code any more - it’s a form of compiled binary that just so happens to be in the same language as the original. ↩︎

Ah sorry, misunderstood you there. Yeah if as a programmer you already order your code in the for you preferred way then you oc dont need this tool at all as your code is already ordered, I simply wrote it because I got tired of maintaining that order in my code over time and thought I wanted a tool that sorts functions and classes just like ruff sorts imports, so that my code stays organized and high in quality over time and someting that I could integrate as a pre commit hook just like other dev tools

Maybe related:

Simplint seems to be a brand new Python code linting tool, and among its linting rules it seems to have one that overlaps with what you are presenting here.

Yes this seems to be related and aims for a very similar thing as it seems. I actually wrote pyorder also to complement my usage of ruff, simplint is obviously cooler as it is written in Rust. I suppose pyorders only advantage is its plugin system which allows a user to write a plugin to customize any behaviour and not just use supression comments.

  1. callers-before-callees: a definition that uses another definition should be defined before it. (Hard dependencies that are needed at definition time are ordered before it, e.g. base classes, arg/kwargs defaults, or decorators).
  2. functions-before-classes: functions should be defined before classes within the module.
  3. visibility-ordering: public before private definitions (e.g., public, _private, __more_private)
  4. alphabetical-ordering: definitions are ordered alphabetically.

Comments:

  1. Mutual recursion: Hofstadters Female and male sequences will break 1.
    1.1. There is also drawing the Dragon curve that can use mutual recursion.
  2. Why functions before classes? if their are grouped definitions then each group may have associated functions and classes - keeping the definitions in their grouping may be more maintainable and would break 2.
  3. Again groupings may have greater meaning than dispersing private definitions in 3.
  4. ugh. It is a backstop ordering, but why change from the non-alphabetic? “When I thought of it” vs alphabetic might make the former have more meaning in 4.

I myself would not use the utility. I hope it has a method of disabling it for a source/sources if someone adds it to CI checks - (Until you hunt that person down :smile:)?

Hi, thanks for the feedback. Mutual recursion is actually handled through graph condensation and both definitions get the same rank, which leaves the following ranks to decide order.

For functions before classes: This is simply a choice I researched and it seems to be most common. If a function is used by a class or a method of that class then it will be ordered below/after it tho and not before as the reference rank decides before this second rank.

Alphabetical was simply the final choice for the final ordering decision. Also in my experience the “When I thought of it” component loses meaning over time as the reasons for are forgotten and then later when you or someone else reads the code again, the ordering reasons at that time are less important than an objective order that is reasonable for most. This applies to most of the rules actually or at least my reasoning for writing this tool at all, as personal ordering choices lose meaning over time, especially when working with others, so an objective forced order helps maintainability a lot, I believe. But the beauty of programming is that no has to use the tool at all if they disagree, although in this case there is a plugin system so you could in fact adjust any ordering policies, remove some or add new ones as you please.

Thanks for taking the time to look at my tool, hope I could explain a bit better, I would be thrilled if you would consider running it on a few files and let me know if it us usable for someone who did not write it himself

This is something that I see very very frequently. An inexperienced programmer starts to recognize a problem (in this case, disorganized code), discovers one potential solution (automatic ordering), and believes that it will solve the problem. Fun fact: It won’t. Tools like black[1] have existed for a long time, and they haven’t solved the problem of disorganized code.

My recommendation? Don’t try to automate away creative decisions. Sure, you might get some “felt benefit” (if that’s a term) in the short term, but it won’t actually help you to make larger projects more manageable. Instead, let the code be what it wants to be. You’re a gardener, not a bulldozer. Yes, sometimes your code will be messy. Sometimes you will have a commit where you do nothing but reorder some things because thisi s a better way to lay them out. That’s fine. By handing that control to an automated tool, you deprive yourself the opportunity to do it better - or perhaps worse, you spend all your time wrestling with the tool, thinking “THIS time it’ll be perfect and my code will be beautiful”. It won’t. Beauty can’t be condensed down to a set of rules; it’s a design decision (or rather, a constant stream of design decisions) that you, the programmer, will be making.

And if you look back on your code from a few years ago and decry it as ugly, what that really means is that you’re a better programmer now than you were. Maybe change some of that code as you make other edits. Or maybe don’t. Either is fine. Your code is your code; this is your garden, your orchard. Being “perfect” (for any definition of perfect) is unattainable; what you want is something that’s good, and productive.


  1. bolding that name isn’t necessary, but it makes it more black, so, enjoy ↩︎

Most likely, but actually implementing their own solution is a great way to gain experience - I hope we haven’t discouraged them too much :slight_smile:

I am actually fairly experienced, and unorganized code is especially a problem in large codebases (speaking from experience) where an enforced type ordering can be very useful, especially over time as new functions, classes and methods are added and the reasons for the original order are forgotten. black is just a formatter and does not hold opinions towards order. I use ruff personally, and pyorder is a complement towards a formatter like black or ruff. You are right that this is very niche and not many people would want to use such a tool as they have their own ways of ordering their code, but if one wanted to have a forced order then smth like pyorder can become very useful, especially with its plugin system that allows a user to customize rules as they like and implement their own desired order fairly simply.

Dont get me wrong your criticism regarding the need for this tool is real, I am aware this is very niche and not a concern to many and if so they have their own ways of dealing with it. But I disagree on some of the things here, for one that the order of code is a question of design, imo order of code is not a design question (which is why wrote the tool), design decisions are imo on the modular level and grouping should be done more within packages and modules and not so much or rather in a limited way within a module. The topdown rule/recommendation exists for a reason.

The tool is niche, I am aware, there are already similar solutions like ssort, but to say this is useless or not needed at all is just incorrect imo, just because you would see no use in it doesnt mean others dont