如何构建 Python 模块以限制导出的符号? [英] How to structure a Python module to limit exported symbols?

查看:30
本文介绍了如何构建 Python 模块以限制导出的符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Python 模块,其目的是导出单个数据结构.我相信这意味着我的模块应该导出单个符号(例如 foo),所有其他符号都带有下划线前缀.

I am writing a Python module whose purpose is to export a single data structure. I believe this means my module should export a single symbol (e.g. foo), with all its other symbols being underscore-prefixed.

生成数据结构需要大量代码 - 我应该如何构建模块以确保此代码中的任何符号都不会在没有前缀的情况下被导出?两种可能的方法是:

Generating the data structure takes a fair amount of code - how should I structure the module to ensure that no symbols within this code are exported without a prefix? Two possible approaches are:

  1. 将生成代码放在顶层,注意在整个过程中使用下划线,例如:

  1. Put the generation code at the top-level, being careful to use underscores throughout, e.g.:

_bar = ...
for _i in ...:
    _bar.append(...)

foo = [_bar, ...]

  • 将生成代码放在返回数据结构的函数中.这仅需要函数名称使用下划线.例如:

  • Put the generation code within a function which returns the data structure. This requires only the function name to use an underscore. For example:

    def _generate_foo():
        bar = ...
        for i in ...:
            bar.append(...)
        return [bar, ...]
    
    foo = _generate_foo()
    

  • 这两种方法中的任何一种都被认为更好吗?或者,有没有其他更好的方法来构建这个模块?

    Is either of these approaches considered better? Or, is there another way to structure this module which would be preferred?

    推荐答案

    请注意,使用下划线只会阻止使用 from module import * 导入该名称(如 记录).它不会以任何真实的方式使名称私有".人们仍然可以通过执行 import modulemodule._hiddenStuff 来查看模块中的所有内容.

    Note that using the underscore only prevents that name from being imported with from module import * (as documented). It doesn't make the name "private" in any real way. People can still see everything in your module by doing import module and then module._hiddenStuff.

    对于您的情况,您应该使用 __all__.让代码随心所欲,但在模块顶部:

    For your case, you should instead use __all__. Have the code be whatever you want, but at the top of the module do:

    __all__ = ['foo'] # foo being the one thing you do want to export
    

    这与使用下划线的效果相同,但当您想排除大多数内容而不是包含它们时效果更好.

    This has the same effect as using underscores but is much better when you want to exclude most things instead of include them.

    这篇关于如何构建 Python 模块以限制导出的符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆