简体   繁体   English

当用户想在Python中使用import *导入所有内容时,如何引发异常?

[英]How do I raise an exception when user wants to import everything using import * in Python?

I want to inhibit user from importing like this: 我想禁止用户这样导入:

from module.sub import *

This should raise and exception and do not let anything come in the namespace unless user imports anything specific like this: 这应该引发和异常,除非用户导入如下特定内容,否则不要让任何内容进入名称空间:

from module.sub import apples

In module.sub : module.sub

__all__ = []

It won't raise an exception, but when someone does from module.sub import * , nothing will be imported module.sub will still be initialized, added to sys.modules , and added to the local namespace, but none of the names defined in module.sub will be added to the namespace. 它不会引发异常,但是当有人from module.sub import * 将不会导入任何 module.sub仍将被初始化,添加到sys.modules以及添加到本地名称空间,但是没有定义任何名称在module.sub中将被添加到名称空间。

You could then refer to module.sub.apples but not apples directly. 然后,您可以直接引用module.sub.apples ,而不直接引用apples


If you really want an exception, at the cost of being a bit confusing, you could do: 如果您确实想要一个例外,但会有点混乱,您可以这样做:

__all__ = ['not_defined']

then: 然后:

>>> from module.sub import *
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'module' object has no attribute 'not_defined'

Luckily the nice folks made python open source so you can certainly do this 幸运的是,好心人将python开源了,因此您当然可以做到这一点

download the appropriate source here https://www.python.org/downloads/source/ 在此处下载适当的源https://www.python.org/downloads/source/

modify import.c , so that it raises an error if it gets the splat... 修改import.c ,使它在遇到碎片时引发错误。

or modify the Grammar to ignore the splat (which will require also changing the Parser 或修改语法以忽略splat(这也需要更改解析器

once you do one of those things simply recompile python and use your new python instead of the standard one (simply recompile may be a bit misleading on the complexity of this step) 一旦您执行了其中一项操作,只需重新编译python并使用新的python而不是标准的python(简单地重新编译可能会误导此步骤的复杂性)

OR MORE SIMPLY JUST USE __ALL__ = [] in your modules __init__.py 或更简单地在模块__init__.py使用__ALL__ = []

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

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