使用外部定义的函数修改模块全局变量
我有一个非常简单的装饰器函数,用于通过模块的 __all__ 属性公开模块中定义的函数。因为我将它用于包内的多个模块,所以我在包的 __init__.py
中定义了它。
因为我无法在定义中使用 __all__
,因为它会引用 __init__.py
模块(或更确切地说是包)的 __all__
,我目前正在这样做:
def expose ( fn ):
fn.__globals__['__all__'].append( fn.__name__ )
这似乎工作得很好。但是我不确定使用 __global__ 属性是否是执行此操作的理想方法,特别是因为该属性似乎没有记录(至少我在文档中找不到有关它的任何内容)。
使用 __globals__ 可以吗?或者是否有一种更简单、更强大的方法来完成这项工作?
编辑:
为了澄清,我不一定需要访问模块的 __all__ 属性。我可以轻松地使用不同的名称并最终得到相同的问题。我只是使用 __all__ ,因为它在模块中保存所有公开对象的目的符合我的意图。但同时我也可以将其命名为 exposedFunctions
或其他名称。所以问题更多的是如何访问模块的全局属性。
I have a very simple decorator function I use to expose functions defined in a module via the module’s __all__
property. Because I use it for multiple modules within a package, I have it defined in the package’s __init__.py
.
Because I cannot use __all__
from within the definition, as it would refer to the __all__
of the __init__.py
module (or rather the package), I am currently doing it like this:
def expose ( fn ):
fn.__globals__['__all__'].append( fn.__name__ )
This seems to work totally fine. However I’m not sure if using the __global__
property is the ideal way to do it, especially as that property seems to be undocumented (at least I couldn’t find anything about it in the documentation).
Is using __globals__
fine for that, or is there maybe an easier and more robust way to make this work?
edit:
For clarification, I don’t necessarily need to access the __all__
property of the module. I can easily use a different name and end up with the same question. I’m just using __all__
because its purpose of holding all exposed objects in a module matches my intention. But at the same time I could also name it exposedFunctions
or whatever. So the question is more about how to access the global properties of the module.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能喜欢 Thomas Rachel 的
AllList
装饰器:从任何地方导入它,然后在模块顶部,
它看起来就像在模块中
,无需担心全局变量。
更新
如果您确实想担心全局变量,请查看在不同模块的上下文中使用类——然而,它并不漂亮。
You might like Thomas Rachel's
AllList
decorator:Import it from whereever, and at the top of your module have
then in your module it looks like
and no need to worry about globals.
Update
If you really want to worry about globals, take a look at Use a class in the context of a different module -- it is not pretty, however.