Modules in Python✌
MODULES IN PYTHON
- 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.
>>> 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 *
User defined modules
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:
- Current directory
- PYTHONPATH
- Default directory
import
sys
print
(sys.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.
Comments
Post a Comment