What is the reason python needs __init__.py for packages? [duplicate]

我的未来我决定 提交于 2021-02-07 08:58:47

问题


I understand that python needs the __ init __.py file in order to recognize the directory as a python package, that way we can import sub modules into our program.I can see the similarity to classes and how init can be used to execute necessary code off the bat.

However, in the python docs, this line confuses me,

This is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

as seen here https://docs.python.org/2/tutorial/modules.html#packages

Could someone please clarify this?


回答1:


The documentation is very clear on this - your project structure could look like this:

app
 - common
  - init.py
 - resources
 - string
 - src

If Python implicitly treated the directories as packages, the "string" directory could present a name clash with Python's built-in string module (https://docs.python.org/2/library/string.html). This means that when calling import string, the module is ambiguous.

__init__.py also adds a bit of functionality: code there is executed when initializing the package and can therefore be used to do package setup of some kind.




回答2:


If you have a directory named string that isn't a package, in a location where Python searches for modules and packages (such as the current working directory), Python shouldn't try to import that when you do import string. The __init__.py requirement lets Python know it should keep going rather than treating that directory as a package.




回答3:


this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

Suppose you have a directory where you do work for school, some of this involving python. You have a directory for math, which you have called math. You also have a python module you wrote, so the top level directory "school" has been added to the python path so you can use it anywhere

School/    
   math/
      hw1.txt
      integrate.py
   MyPythonModule/
      __init__.py
      someClass.py
      someFunc.py

When you are using python later and you are searching for MyPythonModule, python will open up School/

Then it sees math/ and MyPythonModule/ If you are using math in your python program, and there was not a way to distinguish between module ../lib/site-packages/math/ and non module ../School/math/ then python will treat your file ../School/math/ as the package math; breaking code without you knowing why.



来源:https://stackoverflow.com/questions/30018243/what-is-the-reason-python-needs-init-py-for-packages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!