What's difference between python package and module?
MODULE
- Python basic tool for organizing code is the module : mm.py
- Module typically corresponds to a single source file.
- You load module by import keyword : import mm
- imported module is represented by an object of type module : type(mm)
PACKAGE
- Package is a special type of module that contains other modules and packages to group modules with similar functionality.
- package directory has a __init__.py. It is package init file that makes it an module too.
- __init__.py is executed when package is imported
- Package have __path__ but module does not have many python libraries.
- Package is just a directory on filesystem having a __init__.py whereas module is a single python file.
- Module object of package has __path__ attribute but a module that is not package too, will not have __path__ attribute
- __file__ attribute of package returns __init__.py absolute path. Where as it returns module's file name for package.
- In below example urllib is package and request is module
import urllib
import urllib.request
type(urllib)
Out[4]: module
type(urllib.request)
Out[5]: module
urllib.__path__
Out[6]: ['/home/nansari/anaconda3/lib/python3.6/urllib']
urllib.request.__path__
Traceback (most recent call last):
File "<ipython-input-7-5f94591ece52>", line 1, in <module>
urllib.request.__path__
AttributeError: module 'urllib.request' has no attribute '__path__'
DIRECTORY structure for a package
/tmp/dir1
--------/dir2
-------------/path_to_add_in_sys.path
-------------------------------------/pkg_name
----------------------------------------------/__init__.py
export PYTHONPATh=$PYTHONPATH:/tmp/dir1/dir2/path_to_add_in_sys.path
$ mkdir -p /tmp/dir1/dir2/path_to_add_in_sys.path
$ cd /tmp/dir1/dir2/path_to_add_in_sys.path
/tmp/dir1/dir2/path_to_add_in_sys.path$ mkdir pkg_name
$ /tmp/dir1/dir2/path_to_add_in_sys.path
$ cd pkg_name
$ /tmp/dir1/dir2/path_to_add_in_sys.path/pkg_name
$ touch __init__.py
$ cd /tmp
$ export PYTHONPATH=/tmp/dir1/dir2/path_to_add_in_sys.path/
$ python
Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 18:10:19)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg_name
>>> pkg_name.__path__
['/tmp/dir1/dir2/path_to_add_in_sys.path/pkg_name']
>>> >>> pkg_name.__file__
'/tmp/dir1/dir2/path_to_add_in_sys.path/pkg_name/__init__.py'
>>>
Comments
Post a Comment