You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python库中如何隐藏内部类,禁止外部导入访问?

如何隐藏Python库中的内部类(Python 3.6+)

问题背景

我正在编写一个对接REST服务器的Python库,希望通过pip安装后,外部项目导入时无法访问库内的部分类(比如OtherClass)。当前库结构、根目录__init__.py和setup.py内容如下:

库结构

.
├── my_library
    ├── __init__.py
    ├── controller
    |   ├──OtherClass.py
    |   └──Client.py
    └── models
        ├── __init__.py
        └── MyModel.py

根目录__init__.py

from .controller.Client import Client

setup.py

from setuptools import find_packages, setup

setup(
    name='my_library',
    packages=find_packages(include=['my_library']),
    version='0.1.0',
    description='My library',
    author='Pasini Matteo',
    setup_requires=['pytest-runner'],
    license='MIT',
    tests_require=['pytest==4.4.1'],
    test_suite='tests',
)

核心需求:禁止使用者执行如下导入操作:

from my_library.controller.OtherClass import OtherClass

解决方案(Python 3.6+)

1. 遵循私有命名约定(基础)

Python社区默认约定:以下划线_开头的模块、类、函数为内部私有元素,外部不应访问。

  • 将controller/OtherClass.py重命名为controller/_OtherClass.py
  • 将类名OtherClass改为_OtherClass
  • 在库内部需要使用该类的模块(比如Client.py)中,用相对导入调用:
    from ._OtherClass import _OtherClass
    

2. 通过__init__.py限制导出范围

在controller目录下添加__init__.py文件,明确控制对外暴露的内容:

# controller/__init__.py
# 空的__all__表示执行from my_library.controller import *时不会导入任何内容
__all__ = []

保持根目录__init__.py不变,仅导出公共APIClient类:

from .controller.Client import Client

3. 优化setup.py确保内部模块不被误暴露

调整setup.py的find_packages参数,明确包含主包及其子包(内部模块仍需安装供库自身使用),同时依靠__init__.py控制对外暴露的内容:

from setuptools import find_packages, setup

setup(
    name='my_library',
    packages=find_packages(include=['my_library', 'my_library.*']),
    version='0.1.0',
    description='My library',
    author='Pasini Matteo',
    setup_requires=['pytest-runner'],
    license='MIT',
    tests_require=['pytest==4.4.1'],
    test_suite='tests',
)

额外说明

Python本身没有绝对的“私有”机制,上述方法是通过社区约定和导入路径控制,引导用户仅使用库的公共API,避免依赖内部实现细节。

内容的提问来源于stack exchange,提问作者Matteo Pasini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 22:45:40