推荐学习书目
› 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 · May 19, 2022 · 3115 views
    This topic created in 1593 days ago, the information mentioned may be changed or developed.

    昨天突然有的想法,然后试验可行以后就立即做出来了。这个库不仅仅控制 __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 replies  •  2022-05-19 12:34:57 +08:00
    jaredyam
        1
    jaredyam  
       May 19, 2022
    效率真高。大佬如何理解包级暴露、模块级暴露、对象级暴露的差异?
    frostming
        2
    frostming  
    OP
       May 19, 2022
    @jaredyam 前两个本质是一个东西,包暴露就是<package>/__init__模块的暴露

    对象暴露的话我这个没有覆盖到。
    abersheeran
        3
    abersheeran  
       May 19, 2022
    感觉没有什么实际使用的场景,不过挺有意思的。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5082 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 06:45 · PVG 14:45 · LAX 23:45 · JFK 02:45
    ♥ Do have faith in what you're doing.