stay Python In the module of , Imagine C language-written DLL Dynamic link library is the same , You can provide the interface name of the function , You need to use __all__ The variable . Through this feature , You can control which functions are referenced outside , What can't be seen . This is very important for the software of a big project , Because of uncontrolled exposure , Will lead to other software developers misuse , So there are invisible problems between software calls . For example, a component that only gives an interface , It's definitely easier to use than a component that gives you a thousand interfaces . therefore , In the development cooperation of a team , Make sure that such a rule is clear ： Can it be less or more , Enough is good . Expose irrelevant interfaces , It will lead to more problems .
__all__ = ['test1'] def test1(): print("-----test1-----") def test2(): print("-----test2-----")
In this code , Only exposed test1 Interface , and test2 The interface doesn't see . Define at the beginning of the module __all__ Variable ,import After the module , We can only find __all__ A variable or function that exists in , Others cannot be called .
Unlike C perhaps Java,Python No language native visibility controls , It depends on a set of things that we should consciously abide by ” Appointment “ Work under the . For example, the beginning of an underline should not be visible to the outside . Again ,__all__ It is also a convention for module to expose interface , Compared with underscores ,__all__ Provides exposure interface for ” White list “. Some variables that don't start with an underline （ Like from other places import To the current module