Python – Packages and modules:

In this tutorial, we will learn about Modules in Python. Modules in Python are none other than .

python extension files which contains various statements and functions. In order to import a module, we will use the “import” command.

There are many modules in Python. Below are the very few examples just for giving an idea for you.

  1. math – this is a mathematical module
  2. statistics – This is for Statistical functions
  3. pathlib – this is for filesystem paths
  4. urllib – this is for handling urls
  5. zlib – this is for data compression
  6. csv – this is for file reading and writing

The above all are few pre-existing modules which are in python.

We can also write our own modules. Let us see how to create a module which helps us to process the prime numbers under any given value.

First create a file called “prime.py” and write the below code into the file.

def prim(n):

    for x in range(2,n):

            for i in range(2,x):

                    if x%i==0:

                            break

            else:

                    print(x)

 Now connect to python3 and import the module called "prime" using the keyword import. 
Then, call the function by passing the integer value as an argument to list the prime numbers for the given value.
>>> import prime

>>>prime.prim(10)

2

3
5

7

Calling the function with value 20:

>>>prime.prim(20)
2

3

5

7

11

13

17

19

>>>
dir(module_name) will list us all types of variables, modules, funtions used for the given module.
>>>dir(prime)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'prim']

Packages:

Packages are the namespaces within which consists many modules and packages. Every package is none other than a directory that consists a file called “–init__.py”. This file describes the directories as packages.

For example, we have created the prime.py module in the above example. Now let us create the package for the same.

 To create a package, we will to follow the below steps.

  1. first have the module ready, that is prime.py
  2. Create a directory called “primenum” and keep the above module in that directory.
  3. Create a file called __init__.py

Let us try accessing the same.

Now we can import the prime module in 2 ways as below.

>>> import primenum.prime

>>> from primenum import prime