pythonruff

How can I use ruff rules to enforce a particular import style


I changed my code base to always import the python datetime module like this:

import datetime as dt

instead of using

import datetime

or

from datetime import datetime

And we had both those in the codebase! It's confusing because you can't know at this point what datetime can do, if it is the module or the class. See also this blog post by Adam Johnson: https://adamj.eu/tech/2019/09/12/how-i-import-pythons-datetime-module/

What I try to do is create a rule for the ruff linter that enforces this import style. There is tidy-imports but I can't get it to work.


Solution

  • You should be able to lint code using from datetime import datetime syntax to suggest replacing it with import datetime as dt with the TOML configuration:

    [tool.ruff.lint]
    # Add the ICN rules to any others you have selected.
    select = ["E4", "E7", "E9", "F", "ICN"]  
    
    [tool.ruff.lint.flake8-import-conventions]
    banned-from = ["datetime"]
    
    [tool.ruff.lint.flake8-import-conventions.extend-aliases]
    "datetime" = "dt"
    

    Which, for the code:

    import datetime
    from datetime import datetime as dto
    import datetime as dt
    
    print(datetime, dto, dt)
    

    Outputs the errors:

    `datetime` should be imported as `dt` (ICN001) [Ln 1, Col 8]
    Members of `datetime` should not be imported explicitly (ICN003) [Ln2, Col 1]
    

    fiddle

    See unconventional-import-alias (ICN001) and banned-import-from (ICN003)