top
upGrad KnowledgeHut SkillFest Sale!

Search

Python Tutorial

We write functions in program to avoid repetitive use of same code. Further, we learned how to club functions of similar nature in a module. This concept of modular approach is further extended to organizing modules in package. Just as relevant objects such as classes, functions etc. are put in a module; package contains more than one modules. This is something like hierarchical file system in computer disk where we save files and sub-folders of similar nature in one folder.A package is a folder containing one or more modules. In addition to that, the folder must contain a special file called __init__.py which is a packaging list. It serves two purposes. It is necessary for Python interpreter to recognise a folder as package. Secondly it offers only specified resources from its modules to be imported.Once a package having folder structure as described above is created, it can be deployed for system-wide use by running s setup script. The script calls setup() function from setuptools module. What is more, the package can be made publicly importable by uploading it to PyPI repository.First of all let us create a package named as 'example'.Create a new folder named c:\PackageExample and a subfolder in it named as 'example' and save following scripts in example folder.#messages.py def welcome(name):        print ("Hi {}. Welcome to Python Tutorial".format(name))        return def bye(name):        print ("Good Bye {}. See you again".format(name))#area.py def rectangle(w,h):        return w*h def circle(r):        import math        return math.pi*math.pow(r,2)#factorial.py def ifact(x):        f=1        for i in range(1, x+1):                f=f*i        return f def rfact(n):            if n == 1:                return 1        else:                return n * rfact(n-1)Also create an empty text file and name it as __init__.py.Later on we shall also create another Python script in PackageExample folder and import example package in it. The file structure should resemble following diagram:Start Python interpreter by being in PackageExample folder. You can import modules from example folder as shown below:C:\PackageExample>python >>> from example import messages >>> messages.bye("Ravi") Good Bye Ravi. See you again >>> from example import area >>> area.rectangle(10,20) 200It is also possible to import one or more functions from a module in the package>>> from example.messages import welcome >>> welcome("Ravi") Hi Ravi. Welcome to Python TutorialTo choose specific functions from various modules in package and make available for import, add following statements in the empty  __init__.py: #__init__.py from .messages import bye from .area import circle, rectangle from .factorial import ifactOnly the specified functions packages in __init__.py script are available for import now. As shown in the above diagram, create packagetest.py in PackageExample folder:#test.py from example import bye, ifact, circle bye("World") area=circle(5) f=ifact(5) print ("area of circle : ",area) print ("5! = ",f)Note that functions imported from the example package are not identified by their respective module as done earlier.Installing package for system wise useSave following code as setup.py in PackageExample folder. The script imports setup() function from setuptools module. It takes various arguments such as name, version, author, description etc. The zip_safe argument determines whether the package is installed in compressed mode or regular mode.#setup.py from setuptools import setup setup(name='example',      version='0.1',      description='sample package',      url='#',      author='pythonista',      author_email='pythonanytime@gmail.com',      license='MIT',      packages=['example'],      zip_safe=False)To make example package available system-wide, use following command. The pip utility is available in site-packages folder of installation directory of Python. If required, this folder should be included in system path. Note that this command has to be issued while being in C:\PackageExample folder.C:\packageexample>pip install . Processing c:\packageexample Installing collected packages: example Running setup.py install for example ... done Successfully installed example-0.1Now example package can be used from anywhere in file system and can be imported in any script or interpreter.D:\>python >>> import example >>> example.rectangle(10,20) 200Publish Python PackagePython packages are uploaded to PyPI repository (stands for Python Package Index and is hosted at https://pypi.org/) from where users can download and install them.  If you want to publish your package, perform following steps:Create following files in this package folderdescription.txt: a text file containing description of your package.licence.txt: The definition of licence under which package is being distributed.Readme.md: description for github pageChange url attribute in set.py to name of your github repositoryEnsure that you have setuptools and wheel packages installedBuild the distribution archives by following command:python3 setup.py sdist bdist_wheelThis will create following files in dist folder of your packageexample_pkg-0.0.1-py3-none-any.whl example_pkg-0.0.1.tar.gzThe .tar.gz file is the source distribution of package whereas .whl file is the binary distribution.Login to https://github.com/ and create a new repository by the name of your package.Copy files in the package folder in your local computer to this repository.Install twine packagepip install twineRegister at https://pypi.org and login to your account.Navigate to your project folder and use following command to upload package to PyPI repositorytwine upload dist/*You package will now be successfully uploaded to PyPi and it can be installed by anybody using 'pip install' command.
logo

Python Tutorial

Python - Packages

We write functions in program to avoid repetitive use of same code. Further, we learned how to club functions of similar nature in a module. This concept of modular approach is further extended to organizing modules in package. Just as relevant objects such as classes, functions etc. are put in a module; package contains more than one modules. This is something like hierarchical file system in computer disk where we save files and sub-folders of similar nature in one folder.

A package is a folder containing one or more modules. In addition to that, the folder must contain a special file called __init__.py which is a packaging list. It serves two purposes. It is necessary for Python interpreter to recognise a folder as package. Secondly it offers only specified resources from its modules to be imported.

Once a package having folder structure as described above is created, it can be deployed for system-wide use by running s setup script. The script calls setup() function from setuptools module. What is more, the package can be made publicly importable by uploading it to PyPI repository.

First of all let us create a package named as 'example'.

Create a new folder named c:\PackageExample and a subfolder in it named as 'example' and save following scripts in example folder.

#messages.py
def welcome(name):
       print ("Hi {}. Welcome to Python Tutorial".format(name))
       return
def bye(name):
       print ("Good Bye {}. See you again".format(name))
#area.py
def rectangle(w,h):
       return w*h
def circle(r):
       import math
       return math.pi*math.pow(r,2)
#factorial.py
def ifact(x):
       f=1
       for i in range(1, x+1):
               f=f*i
       return f
def rfact(n):    
       if n == 1:
               return 1
       else:
               return n * rfact(n-1)

Also create an empty text file and name it as __init__.py.

Later on we shall also create another Python script in PackageExample folder and import example package in it. The file structure should resemble following diagram:

Start Python interpreter by being in PackageExample folder. You can import modules from example folder as shown below:

C:\PackageExample>python
>>> from example import messages
>>> messages.bye("Ravi")
Good Bye Ravi. See you again
>>> from example import area
>>> area.rectangle(10,20)
200

It is also possible to import one or more functions from a module in the package

>>> from example.messages import welcome
>>> welcome("Ravi")
Hi Ravi. Welcome to Python Tutorial

To choose specific functions from various modules in package and make available for import, add following statements in the empty  

__init__.py:
#__init__.py
from .messages import bye
from .area import circle, rectangle
from .factorial import ifact

Only the specified functions packages in __init__.py script are available for import now. As shown in the above diagram, create packagetest.py in PackageExample folder:

#test.py
from example import bye, ifact, circle
bye("World")
area=circle(5)
f=ifact(5)
print ("area of circle : ",area)
print ("5! = ",f)

Note that functions imported from the example package are not identified by their respective module as done earlier.

Installing package for system wise use

Save following code as setup.py in PackageExample folder. The script imports setup() function from setuptools module. It takes various arguments such as name, version, author, description etc. The zip_safe argument determines whether the package is installed in compressed mode or regular mode.

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

To make example package available system-wide, use following command. The pip utility is available in site-packages folder of installation directory of Python. If required, this folder should be included in system path. Note that this command has to be issued while being in C:\PackageExample folder.

C:\packageexample>pip install .
Processing c:\packageexample
Installing collected packages: example
Running setup.py install for example ... done
Successfully installed example-0.1

Now example package can be used from anywhere in file system and can be imported in any script or interpreter.

D:\>python
>>> import example
>>> example.rectangle(10,20)
200

Publish Python Package

Python packages are uploaded to PyPI repository (stands for Python Package Index and is hosted at https://pypi.org/) from where users can download and install them.  If you want to publish your package, perform following steps:

  • Create following files in this package folder
    • description.txt: a text file containing description of your package.
    • licence.txt: The definition of licence under which package is being distributed.
    • Readme.md: description for github page
  • Change url attribute in set.py to name of your github repository
  • Ensure that you have setuptools and wheel packages installed
  • Build the distribution archives by following command:
python3 setup.py sdist bdist_wheel

This will create following files in dist folder of your package

example_pkg-0.0.1-py3-none-any.whl
example_pkg-0.0.1.tar.gz

The .tar.gz file is the source distribution of package whereas .whl file is the binary distribution.

  • Login to https://github.com/ and create a new repository by the name of your package.
  • Copy files in the package folder in your local computer to this repository.
  • Install twine package
pip install twine
  • Register at https://pypi.org and login to your account.
  • Navigate to your project folder and use following command to upload package to PyPI repository
twine upload dist/*

You package will now be successfully uploaded to PyPi and it can be installed by anybody using 'pip install' command.

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

Eula

This is my first time here. I am truly impressed to read all this in one place.

Jaypee Dela Cruz

Thank you for your wonderful codes and website, you helped me a lot especially in this socket module. Thank you again!

lucky verma

Thank you for taking the time to share your knowledge about using python to find the path! Your insight and guidance is greatly appreciated.

Pre Engineered Metal Building

Usually I by no means touch upon blogs however your article is so convincing that I by no means prevent myself to mention it here.

Pre Engineered Metal Building

Usually, I never touch upon blogs; however, your article is so convincing that I could not prevent myself from mentioning how nice it is written.

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses the .Net Framework. It utilizes the Common Language Interface (CLI) that describes the executable code as well as the runtime environment. C# can be used for various applications such as web applications, distributed applications, database applications, window applications etc.For greater understanding of this tutorial, a basic knowledge of object-oriented languages such as C++, Java etc. would be beneficial.
C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses ...

Read More