Modules in Python✌

 


MODULES IN PYTHON


Modules are simply a ‘program logic’ or a ‘python script’ that can be used for variety of applications or functions. We can declare functions, classes etc in a module.

  • A module allows you to logically organize your Python code.
  • Grouping related code into a module makes the code easier to understand and use. 
  • A module is a Python object with arbitrarily named attributes that you can bind and reference.
  • Consider a module to be the same as a code library.
  • A file containing a set of functions you want to include in your application.
Modules refer to a file containing Python statements and definitions.

A file containing Python code, for example: test.py, is called a module, and it is advisable to always use lower case letters in user-defined module name .

We use modules to break down large programs into small manageable and organized files. 

Modules provide re-usability of code.

We can define our most used functions in a module and import it, instead of copying their definitions into different programs.

Types of Modules

Built-in modules

>>> help('modules') 

IPython             _weakrefset         heapq               secrets
__future__          _winapi             hmac                select
_abc                abc                 html                selectors
_ast                aifc                http                setuptools
_asyncio            antigravity         idlelib             shelve
_bisect             argparse            imaplib             shlex
_blake2             array               imghdr              shutil
_bootlocale         ast                 imp                 signal
_bz2                asynchat            importlib           simplegeneric
_codecs             asyncio             ind                 site
_codecs_cn          asyncore            inspect             six
_codecs_hk          atexit              io                  smtpd
_codecs_iso2022     audioop             ipaddress           smtplib
_codecs_jp          autoreload          ipython_genutils    sndhdr
_codecs_kr          backcall            itertools           socket
_codecs_tw          base64              jedi                socketserver
_collections        bdb                 json                sqlite3
_collections_abc    binascii            keyword             sre_compile
_compat_pickle      binhex              lib2to3             sre_constants
_compression        bisect              linecache           sre_parse
_contextvars        builtins            locale              ssl
_csv                bz2                 logging             stat
_ctypes             cProfile            lzma                statistics
_ctypes_test        calendar            macpath             storemagic
_datetime           cgi                 mailbox             string
_decimal            cgitb               mailcap             stringprep
_distutils_findvs   chunk               marshal             struct
_dummy_thread       cmath               math                subprocess
_elementtree        cmd                 mimetypes           sunau
_functools          code                mmap                symbol
_hashlib            codecs              modulefinder        sympyprinting
_heapq              codeop              msilib              symtable
_imp                collections         msvcrt              sys
_io                 colorama            multiprocessing     sysconfig
_json               colorsys            netrc               tabnanny
_locale             compileall          nntplib             tarfile
_lsprof             concurrent          nt                  telnetlib
_lzma               configparser        ntpath              tempfile
_markupbase         contextlib          nturl2path          test
_md5                contextvars         numbers             tests
_msi                copy                opcode              textwrap
_multibytecodec     copyreg             operator            this
_multiprocessing    crypt               optparse            threading
_opcode             csv                 os                  time
_operator           ctypes              parser              timeit
_osx_support        curses              parso               tkinter
_overlapped         cythonmagic         pathlib             token
_pickle             dataclasses         pdb                 tokenize
_py_abc             datetime            pickle              trace
_pydecimal          dbm                 pickleshare         traceback
_pyio               decimal             pickletools         tracemalloc
_queue              decorator           pip                 traitlets
_random             difflib             pipes               tty
_sha1               dis                 pkg_resources       turtle
_sha256             distutils           pkgutil             turtledemo
_sha3               doctest             platform            types
_sha512             dummy_threading     plistlib            typing
_signal             easy_install        poplib              unicodedata
_sitebuiltins       email               posixpath           unittest
_socket             encodings           pprint              urllib
_sqlite3            ensurepip           profile             uu
_sre                enum                prompt_toolkit      uuid
_ssl                errno               pstats              venv
_stat               faulthandler        pty                 warnings
_string             filecmp             py_compile          wave
_strptime           fileinput           pyclbr              wcwidth
_struct             fnmatch             pydoc               weakref
_symtable           formatter           pydoc_data          webbrowser
_testbuffer         fractions           pyexpat             winreg
_testcapi           ftplib              pygments            winsound
_testconsole        functools           queue               wsgiref
_testimportmultiple gc                  quopri              xdrlib
_testmultiphase     genericpath         random              xml
_thread             getopt              re                  xmlrpc
_threading_local    getpass             reprlib             xxsubtype
_tkinter            gettext             rlcompleter         zipapp
_tracemalloc        glob                rmagic              zipfile
_warnings           gzip                runpy               zipimport
_weakref            hashlib             sched               zlib

The above list contains all the modules available in python. The most frequently used modules are highlighted in the above list.

These modules can be used in our python scripts or file using import statement.

  • import module_name
  • import module_name as alias_name
  • from module_name import method_name
  • from module_name import *
Example

# importing built in module math
import math
 
# using square root(sqrt) function contained
# in math module
print(math.sqrt(25))
 
# using pi function contained in math module
print(math.pi)

Output

>> 5.0
3.14159265359

Example

# importing built in module random
import random as rd
 
# printing random integer between 0 and 5
print(rd.randint(0, 5)) 

Output

>> 4

User defined modules

Creating a module is similar to writing a python script .The script should be saved with .py extension. 

Example

Create a file called Car.py with the following code:

Filename : Car.py

class Car:
	brand_name = "BMW"
	model = "Z4"
	manu_year = "2020"

	def __init__(self, brand_name, model, manu_year):
		self.brand_name = brand_name
		self.model = model
		self.manu_year = manu_year

	def car_details(self):
		print("Car brand is ", self.brand_name)
		print("Car model is ", self.model)
		print("Car manufacture year is ", self.manu_year)
			
			
	def get_Car_brand(self):
		print("Car brand is ", self.brand_name)

	def get_Car_model(self):
		print("Car model is ", self.model) 

In the file Car.py , there are attributes brand_name, model and manu_year. The functions defined inside the class are car_details(), get_Car_brand(), get_Car_model().

Let us now use the file Car.py as a module in another file called display.py.

Filename : display.py

import Car as car
car_det = car.Car("BMW","Z5", 2020)
print(car_det.brand_name)
print(car_det.car_details())
print(car_det.get_Car_brand())
print(car_det.get_Car_model())

Output:

BMW
Car brand is  BMW
Car model is  Z5
Car manufacture year is  2020
Car brand is  BMW
Car model is  Z5

So we can access all the variables and functions from Car.py using Car module.

Python Module Path

When we import a module, the interpreter looks for the module in the build-in modules directories in sys.path and if not found, it will look for the module in the following order:

  1. Current directory
  2. PYTHONPATH
  3. Default directory

import sys
 
print(sys.path)

To add Your file path to the system path.You can use


m_directory="home/python_files"
sys.path.append(m_directory)

When you run the above code, you will get the list of directories. You can make changes in the list to create your own path. 

Properties of Module and command prompt

1. when path is changed in the cmd then to apply that change,reload the module imported, so that cache forgets the current values and make a change.

 The following code can be taken as a illustration:

    import imp

    imp.reload(test1)

2. __name__ inbuilt special function of module is used by the cmd to detect the flow of code in the system and return if the code is imported or directly run .

import My_module

print(Sample.__name__)   # My_module

3. __cache__ inbuilt special function is used by module to work on the compiled code.

4. The dir() function

The dir() built-in function returns a sorted list of strings containing the names defined by a module. The list contains the names of all the modules, variables, and functions that are defined in a module.

#  Import built-in module  random
from random import *
 
print(dir(random))

Output:

[‘__call__’, ‘__class__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, 

‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, 

‘__le__’, ‘__lt__’, ‘__module__’, ‘__name__’, ‘__ne__’, ‘__new__’, ‘__qualname__’, 

‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__self__’, ‘__setattr__’, ‘__sizeof__’, 

‘__str__’, ‘__subclasshook__’, ‘__text_signature__’]












Comments

Popular posts from this blog

Access Modifiers in Python✌