PyCharm 程序 __all__ 生成和语法高亮

PyCharm procedural __all__ generation and syntax highlighting

我正在使用这个装饰器以 DRY 方式管理 __all__

def export(obj):
    mod = sys.modules[obj.__module__]
    if hasattr(mod, '__all__'):
        mod.__all__.append(obj.__name__)
    else:
        mod.__all__ = [obj.__name__]

    return obj

对于使用 import * 导入的名称,PyCharm 会发出 unresolved reference 错误,这是可以理解的,因为它不会 运行 分析之前的代码。但这是一个明显的不便。

你会如何解决(或者可能已经解决)?

我的假设:

您可能对另一种管理方法感兴趣 __all__:

https://pypi.org/project/auto-all/

这提供了一个 start_all()end_all() 函数来放置在您的模块中您想要使其可访问的项目周围。此方法适用于 PyCharms 代码检查。

from auto_all import start_all, end_all

# Imports outside the start and end function calls are not included in __all__.
from pathlib import Path

def a_private_function():
    print("This is a private function.")

# Start defining externally accessible objects.
start_all(globals())

def a_public_function():
    print("This is a public function.")

# Stop defining externally accessible objects.
end_all(globals())

我觉得这是一种管理 __all__ 的合理方法,而且我在更复杂的包中使用过这种方法。该包的源代码很小,因此可以很容易地直接包含在您的代码中,以避免需要时的外部依赖。

我使用它的原因是我有一些模块,其中很多项目需要 "exported" 并且我想将导入的项目排除在导出列表之外。我有多个开发人员在处理代码,很容易添加新项目而忘记将它们包含在 __all__ 中,因此自动化会有所帮助。