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.
- math – this is a mathematical module
- statistics – This is for Statistical functions
- pathlib – this is for filesystem paths
- urllib – this is for handling urls
- zlib – this is for data compression
- 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
Calling the function with value 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.
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'prim']
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.
- first have the module ready, that is prime.py
- Create a directory called “primenum” and keep the above module in that directory.
- 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