astral-sh / ruff

An extremely fast Python linter and code formatter, written in Rust.
https://docs.astral.sh/ruff
MIT License
31.46k stars 1.05k forks source link

Rule for PEP 515 - Underscores in Numeric Literals #12787

Open guillp opened 1 month ago

guillp commented 1 month ago

I would like to implement a rule for PEP 515. This allows using underscores as visual separators in numerics. Large numbers are hard to read and using underscore as thousands, millions, etc. separators increases readability a lot.

E.g this would turn this:

my_large_int = 313391313513489341

into:

my_large_int = 313_391_313_513_489_341

A few things I have in mind:

I did not find any prior art so if such a rule exists somewhere else, feel free to point me to it as well.

This would be my first Ruff rule and one of my first experiments with Rust, so I'm looking for feedback about the rule itself before I start coding it. If you feel this is not implementable for any reason, just let me know as well :)

MichaReiser commented 1 month ago

Thanks for the rule idea.

https://github.com/astral-sh/ruff/issues/3693 covers the handling of large numbers. The issue also points out that one challenge with such a rule is that different cultures use different grouping. That means the rule has to be configurable (although we could decide to skip this initially). It would be great to have a design for how different culture norms could be supported by the rule.

In my opinion, hexadecimal and binary numbers should have their own rules. I can see users who want to enforce strict number formatting but want more freedom when it comes to binary notation. The good thing is that it means we can add those rules one by one.

My only concern with these rules is that they potentially overlap with the formatter. Although I think it's unlikely that the formatter wants to be opinionated about the formatting.

@AlexWaygood what's your take on these rules?