简体   繁体   中英

How to block intra package imports

I'm building a python application and my codebase has the following structure:

/utils
  /foo
/package_1
  /foo
/package_2
  /foo
/whatever

I would like to enforce the following rules:

  1. In utils package is possible to import only from utils package itself
  2. In package_1 is possible to import from utils and package_1 itself
  3. In package_2 is possible to import from utils and package_2 itself
  4. In whatever you can import from all the other packages

Which automatic strategy can I use to enforce this coding rule?

It's worth to try flake8-import-graph .

If you want some runtime checks, you can write a custom module importer. See import-hooks and an the examples .

I would go with static analysis. That is, don't enforce this at runtime. You can use this along with tools for linting and testing your code.

My approach would be to adapt the scope example for import analysis from the LibCST project to enforce your import requirements.

https://libcst.readthedocs.io/en/latest/scope_tutorial.html

AFAIK, you can't prevent someone from importing something that is found in his path, but you can modify the path to not include what you don't want to be accessible. I don't recommend it but it is feasible...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM