最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How can I use ruff rules to enforce a particular import style - Stack Overflow

programmeradmin0浏览0评论

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: /

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.

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.

Share Improve this question asked Mar 13 at 13:22 MichielBMichielB 4,3341 gold badge31 silver badges39 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 2

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)

发布评论

评论列表(0)

  1. 暂无评论