Python: 'Private' module in a package

前端 未结 5 783
小蘑菇
小蘑菇 2020-12-05 06:23

I have a package mypack with modules mod_a and mod_b in it. I intend the the package itself and mod_a to be imported free

5条回答
  •  生来不讨喜
    2020-12-05 07:03

    One thing to be aware of in this scenario is indirect imports. If in mypack you

    from mypack._mod_b import foo
    foo()
    

    Then a user can

    from mypack import foo
    foo()
    

    and be none the wiser. I recommend importing as

    from mypack import _mod_b
    _mod_b.foo()
    

    then a user will immediately see a red flag when they try to

    from mypack import _mod_b
    

    As for actual directory structure, you could even extend Jeremy's answer into a _package_of_this_kind package, where anything in that can have any 'access modifiers' on it you like - users will know there be dragons

提交回复
热议问题