简体   繁体   English

如何阻止内部 package 进口

[英]How to block intra package imports

I'm building a python application and my codebase has the following structure:我正在构建一个 python 应用程序,我的代码库具有以下结构:

/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 itselfutils package 只能从utils package 本身导入
  2. In package_1 is possible to import from utils and package_1 itselfpackage_1中可以从utilspackage_1本身导入
  3. In package_2 is possible to import from utils and package_2 itselfpackage_2中可以从utilspackage_2本身导入
  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 .值得一试flake8-import-graph

If you want some runtime checks, you can write a custom module importer.如果你想要一些运行时检查,你可以编写一个自定义模块导入器。 See import-hooks and an the examples .请参阅import-hooks示例

I would go with static analysis.我将 go 与 static 分析。 That is, don't enforce this at runtime.也就是说,不要在运行时强制执行此操作。 You can use this along with tools for linting and testing your code.您可以将其与工具一起用于 linting 和测试代码。

My approach would be to adapt the scope example for import analysis from the LibCST project to enforce your import requirements.我的方法是调整 scope 示例,用于从 LibCST 项目进行导入分析,以强制执行您的导入要求。

https://libcst.readthedocs.io/en/latest/scope_tutorial.html 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. AFAIK,您无法阻止某人导入在其路径中找到的内容,但您可以修改路径以不包含您不想访问的内容。 I don't recommend it but it is feasible...我不推荐它,但它是可行的......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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