1.

Explain the concept of packages in Python

Answer»

A module in Python is a Python script that may have DEFINITIONS of class, functions, variables ETC. having certain SIMILAR nature or intended for a common purpose. For example math module in Python LIBRARY contains all frequently required mathematical functions. This MODULAR approach is taken further by the concept of package. A package may contain multiple modules or even subpackages which may be a part of resources required for a certain purpose. For example Python library’s Tkinter package contains various modules that contain functionality required for building GUI.

Hierarchical arrangement of modules and subpackages is similar to the operating system’s file system. Access to a certain file in the file tree is obtained by using ‘/’. For example a file in a certain folder may have its path as c:\newdir\subdir\file.py. Similarly a module in newdir package will be named as newdir.subdir.py

For Python to recognize any folder as a package, it must have a special file named __init__.py which may or may not be empty and also serves as a packaging list by specifying resources from its modules to be imported.

Modules and their contents in a package can be imported by some script which is at the same level. If we have a.py, b.py and c.py modules and __init__.py file in a test folder under newdir folder, one or more modules can be imported by test.py in newdir as under:

#c:/newdir/test.py from test import a a.hello() #to import specific function from test.a import hello hello()

The __init__.py file can be customized to allow package level access to functions/classes in the modules under it:

#__init__.py from .a import hello from .b import sayhello

Note that hello() function can now be access from the package instead of its module

#test.py import test test.hello()

The test package is now being used by a script which is at the same level as the test folder. To make it available for system-wide use, prepare the following setup script:

#setup.py from setuptools import setup setup(name='test',      version='0.1',      description='test package',      url='#',      author='....',      author_email='...@...',      license='MIT',      packages=['test'],      zip_safe=False)

To install the test package:

C:\newdir>pip install .

Package is now available for import from anywhere in the file system. To make it publicly available, you have to upload it to PyPI repository.



Discussion

No Comment Found