what is __init__.py for?

Python defines two types of packages. regular packages and namespace packages. Regular packages are traditional packages as they existed in python3.2 and earlier. A regular package is typically implemented as a directory containing an __init__.py file. When a regular package is imported, this __init__.py file is implicitly executed, and the objects it defines are bound to names in the package's namespace. The __init__.py file can contain the same python code that any other module can contain, and python will add some additional features to the module when it is imported.

 

python searches a list of directories to resolve names in e.g., import statements. Because these can be any direcotry, and arbitary ones can be added by the end user, the developers have to worry about directories that happen to share a name with a valid python module, such as string in the docs example. To alleviate this, it ignores directories which do not contain a file named __init__.py, even if it is blank.

 

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.pathsys.path is initialized from these locations:

  • the directory containing the input script (or the current directory).

  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).

  • the installation-dependent default.

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值