Python __init__.py vs sys.path.append/insert

后端 未结 1 792
天涯浪人
天涯浪人 2021-02-09 11:07

I know there are a ton of how-to import Python modules not in path, but I have yet to come across using Python\'s __init.py__ vs sys.path.insert. Which method is better? Are the

相关标签:
1条回答
  • 2021-02-09 11:48

    __init__.py is used by the python interpreter to treat directories as packages. Packages play an important role in avoiding namespace collisions. If you read the section 6.4 Packages from Python Modules, it helps to prevent directories with a common name from hiding other valid modules that occur later in the search path.

    Hence, the package mechanism simplifies the task of importing packages. By using an __init__.py you can also do something like from package.subpackage import * which would be difficult or tedious to do if we were to keep appending to sys.path (in fact we will have to append all the possible modules).

    As to answer the second part to your question - why do we need to do anything to treat directories as packages - well, there needs to be some way to tell python what should be allowed to import and what should not be. Also, you do not need to append anything to sys.path explicitly in case you have imported all the required modules at the beginning and that the modules you require to be imported are already present on the PYTHONPATH environment variable.

    Hopefully this answer sheds some light on your query.

    0 讨论(0)
提交回复
热议问题