astral-sh / ruff

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

Support globbing in `banned-api` #2660

Open charliermarsh opened 1 year ago

charliermarsh commented 1 year ago

E.g., top should match import top, but not import top.internal, whereas top.* should match both (I think? We'll do whatever flake8-tidy-imports does).

See: #2656.

not-my-profile commented 1 year ago

No ... I don't think that's a good idea because import top.internal also imports top.

charliermarsh commented 1 year ago

Yes good point! I agree that we shouldn't implement the submodule semantics described above. It was a lazy example.

The question here is really: what does flake8-tidy-imports do? And do we want to support that? (E.g., do we want to support globbing like example.*.truck, as in flake8-tidy-imports?)

(I don't really want to support it, and I won't be working on it any time soon, but that's the intent of the issue.)

seamuswn commented 7 months ago

We have a Python monorepo in my org, where we have developed shared abstractions built under src.core. Ideally we would like to prevent importing private / internal packages within that core package. Specifically restricting subpackages at any level within src.core named 'internal' (i.e. src.core.*.internal), or any subpackages where the package name starts with _ (i.e. src.core._*/src.core.*._*).

I think this would be a useful feature for that type of use case, where we want to import restrictions based on our package structure

ashrub-holvi commented 5 months ago

I have probably similar idea __init__ file is a sort of public interface of a package, so outside of package nobody should do from mypackage.xxx import yyy, they should do from mypackage import yyy only. Tried to do

[tool.ruff.lint.flake8-tidy-imports.banned-api]
"mypackage.*.*".msg = "Import from mypackage"

but was not able to make it work.

Avasam commented 3 months ago

If globbing (or at least submodules) support is added to https://docs.astral.sh/ruff/rules/banned-api/ (TID251), could it also be added to https://docs.astral.sh/ruff/rules/banned-module-level-imports/ (TID253) ? I'd like to configure it like such:

[lint.flake8-tidy-imports]
banned-module-level-imports = [
    # platform-specific imports
    "android",
    "jnius",
    "platformdirs.android", # still allowing top-level platformdirs
    "platformdirs.linux" ,# still allowing top-level platformdirs
    "platformdirs.macos", # still allowing top-level platformdirs
    "platformdirs.windows", # still allowing top-level platformdirs
    "winreg",
]

And at this point, https://docs.astral.sh/ruff/rules/banned-import-from/ (ICN003) as well.