V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
frostming
V2EX  ›  Python

Modul: 像 CommonJS 那样控制模块的导出成员

  •  1
     
  •   frostming ·
    frostming · 2022-05-19 09:59:09 +08:00 · 1833 次点击
    这是一个创建于 679 天前的主题,其中的信息可能已经有所发展或是发生改变。

    昨天突然有的想法,然后试验可行以后就立即做出来了。这个库不仅仅控制 __all__ 变量,而且严格控制导出的成员,未导出的成员则获取不到。

    例子:

    # mymodule.py
    from modul import exports
    
    
    @exports
    def foo():
        return 42
    
    
    baz = "unexported"
    bar = "hello"
    
    exports.bar = bar
    

    调用:

    >>> import mymodule
    >>> mymodule.foo()
    42
    >>> mymodule.bar
    "hello"
    >>> mymodule.baz
    AttributeError: Module 'test' has no attribute 'baz'
    >>> mymodule.__all__
    ['foo', 'bar']
    

    除此之外还支持所有 dict API 以及 modul.exports = ... 整体赋值。

    作为一个玩具项目,也不知会不会有什么用。

    项目地址: https://github.com/frostming/modul

    3 条回复    2022-05-19 12:34:57 +08:00
    jaredyam
        1
    jaredyam  
       2022-05-19 10:59:51 +08:00
    效率真高。大佬如何理解包级暴露、模块级暴露、对象级暴露的差异?
    frostming
        2
    frostming  
    OP
       2022-05-19 11:18:39 +08:00
    @jaredyam 前两个本质是一个东西,包暴露就是<package>/__init__模块的暴露

    对象暴露的话我这个没有覆盖到。
    abersheeran
        3
    abersheeran  
       2022-05-19 12:34:57 +08:00
    感觉没有什么实际使用的场景,不过挺有意思的。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3043 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:38 · PVG 22:38 · LAX 07:38 · JFK 10:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.