The role of the global variable "__all__" when the Python module is imported __python

Source: Internet
Author: User

A py file in Python is a module, and the "__all__" variable is a special variable that can appear in the Py file or in the __init__.py of the package.

1. When used in a common module, it indicates which attributes in a module can be imported into other modules.

such as: global variables, Functions, classes. as follows, test1.py and main.py

test1.py

__all__=["Test"
def Test ():
	print ('----test-----')

def test1 ():
	print ('----test1----')

main.py

From test1 Import *


def main ():
	test ()

	#test1 ()

main ()

Two files are in the same directory.

The result of executing the Python main.py at this point is as follows:


However, if you release the main.py annotation, the following:


Then the __all__ variable in the module is to limit or specify the functions that can be imported into other modules, classes, global variables, etc., if specified then only those that can be imported, without specifying the default is all can import, of course, private properties should be excluded.

2, in the __init__.py under the package

sound/effects/__init__.py Add __all__ = ["echo", "surround", "reverse"]

Then the three modules above will be included in the From sound.effects import *. When __init__.py is empty, just import the package, not the import module.

Some initialization content can be performed in __init__.py, such as:

From. Import Test1 imports the Test1 module in the current directory

From.. Import Test imports the test module in the previous level directory

Because the package is imported, the __init__.py file is executed first.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.