Is closing Python a good substitute for __all__?

Is it possible to use closure instead __all__to restrict the names opened by the Python module? This would prevent programmers from accidentally using the wrong name for module ( import urllib; urllib.os.getlogin()), as well as avoiding contamination of the namespace " from x import *" like __all__.

def _init_module():
   global foo
   import bar
   def foo():
       return bar.baz.operation()
   class Quux(bar.baz.Splort): pass
_init_module(); del _init_module

vs. same module with __all__:

__all__ = ['foo']
import bar
def foo():
    return bar.baz.operation()
class Quux(bar.baz.Splort): pass

Functions can simply adopt this style to avoid contamination of the module namespace:

def foo():
    import bar
    bar.baz.operation()

, API API . , , IPython __all__ , IDE, , .

+3
3

, .

__all__ - Python, , . , , .

, , . , , , , , __all__.

EDIT: , , .

Python . from the_module_name import *, , . , , , .

, , __all__.

+7

from x import * , NameErrors, . " " , , .

. IDE, , ..

"" . , . "" ( ), , . .

+4

, . . .

:

# module named "foo.py"
def _bar():
    return 5

def foo():
    return _bar() - 2 

:

# module named "fooclosure.py"
def _init_module():
    global foo
    def _bar():
        return 5

    def foo():
        return _bar() - 2

_init_module(); del _init_module

:

>>> import foo
>>> dir(foo)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '_bar', 'foo']
>>>
>>> import fooclosure
>>> dir(fooclosure)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'foo']
>>>

. foo() _bar(), _bar() , foo() . foo() _bar() , .

, foo() _bar(), . , ... , _bar(), , , _bar() ?

+1

Source: https://habr.com/ru/post/1721216/


All Articles