Skip to main content

Python Modules

Modules is collection of class and methods. used of those module in our program there are need to include (import) that. after that we capable to use function attributes in our program. In this post we are learn about how to use python packages in our program.

Perdefind Modules

Python are provides large number of modules, that module are available when install python. that package are very useful because that are reduce programmer efforts and save coding time. let view this example to display all available python modules.

#displaying all available modules
Please wait a moment while I gather a list of all available modules...

Please wait a moment while I gather a list of all available modules...

BaseHTTPServer      audiodev            imputil             shelve
Bastion             audioop             indicator_keyboard  shlex
CDROM               base64              inspect             shutil
CGIHTTPServer       bdb                 io                  signal
Canvas              binascii            ipaddress           signatures
ConfigParser        binhex              itertools           site
Cookie              bisect              json                sitecustomize
Crypto              bottle              keyword             six
DLFCN               bottle_server       lib2to3             smtpd
Dialog              bsddb               linecache           smtplib
DocXMLRPCServer     bz2                 linuxaudiodev       sndhdr
FileDialog          cPickle             locale              socket
FixTk               cProfile            lockfile            softwareproperties
HTMLParser          cStringIO           logging             spwd
IN                  cachecontrol        lsb_release         sqlite3
LIVE_exec_js        caches              macpath             sre
LIVE_exec_py2       calendar            macurl2path         sre_compile
LIVE_exec_py3       cgi                 mailbox             sre_constants
MimeWriter          cgitb               mailcap             sre_parse
Queue               chardet             markupbase          ssl
ScrolledText        chunk               marshal             stat
SimpleDialog        cmath               math                statvfs
SimpleHTTPServer    cmd                 md5                 string
SimpleXMLRPCServer  code                mhlib               stringold
SocketServer        codecs              mimetools           stringprep
StringIO            codeop              mimetypes           strop
TYPES               collections         mimify              struct
Tix                 colorama            mmap                subprocess
Tkconstants         colorsys            modulefinder        sunau
Tkdnd               command             multifile           sunaudio
Tkinter             commands            multiprocessing     symbol
UserDict            compileall          mutex               symtable
UserList            compiler            mysql               syntax_err_survey
UserString          contextlib          netrc               sys
_LWPCookieJar       contrib             new                 sysconfig
_MozillaCookieJar   cookielib           nis                 syslog
__builtin__         copy                nntplib             tabnanny
__future__          copy_reg            ntpath              talloc
_abcoll             crypt               nturl2path          tarfile
_ast                csv                 numbers             telnetlib
_backport           ctypes              opcode              tempfile
_bisect             curl                operator            termios
_bsddb              curses              optparse            test
_codecs             datetime            os                  textwrap
_codecs_cn          dbhash              os2emxpath          this
_codecs_hk          dbm                 ossaudiodev         thread
_codecs_iso2022     debconf             packages            threading
_codecs_jp          decimal             packaging           time
_codecs_kr          difflib             paramiko            timeit
_codecs_tw          dircache            parser              tkColorChooser
_collections        dis                 pdb                 tkCommonDialog
_csv                distlib             pexpect             tkFileDialog
_ctypes             distutils           pg_encoder          tkFont
_ctypes_test        doctest             pg_logger           tkMessageBox
_curses             doctest_exec        pickle              tkSimpleDialog
_curses_panel       doctest_reader      pickletools         toaiff
_elementtree        doctest_splitter    pip                 token
_functools          dumbdbm             pipes               tokenize
_hashlib            dummy_thread        pkg_resources       tool
_heapq              dummy_threading     pkgutil             trace
_hotshot            easy_install        platform            traceback
_io                 ecdsa               plistlib            treeadapters
_json               email               popen2              treebuilders
_locale             encodings           poplib              treewalkers
_lsprof             ensurepip           posix               trie
_md5                errno               posixfile           ttk
_multibytecodec     error_log           posixpath           tty
_multiprocessing    eureka_survey       pprint              turtle
_osx_support        exceptions          profile             types
_pyio               extern              progress            unicodedata
_random             fcntl               pstats              unittest
_sha                filecmp             pty                 urllib
_sha256             fileinput           ptyprocess          urllib2
_sha512             filters             pwd                 urllib3
_socket             fnmatch             py_compile          urlparse
_sqlite3            formatter           pyclbr              user
_sre                fpectl              pycurl              util
_ssl                fpformat            pydoc               uu
_strptime           fractions           pydoc_data          uuid
_struct             ftplib              pyexpat             viz_interaction
_symtable           functools           pyodbc              warnings
_sysconfigdata      future_builtins     pyparsing           wave
_sysconfigdata_nd   gc                  pysqlite2           weakref
_testcapi           generate_json_trace quopri              web_exec_c
_threading_local    genericpath         random              web_exec_cpp
_vendor             getopt              re                  web_exec_java
_warnings           getpass             readline            web_exec_js
_weakref            gettext             repr                web_exec_py2
_weakrefset         glob                requests            web_exec_py3
abc                 grp                 resource            web_exec_py3anaconda
add_cache_busting_query_strings gzip                retrying            web_exec_ruby
aifc                hashlib             rexec               web_exec_ts
antigravity         heapq               rfc822              webbrowser
anydbm              hmac                rlcompleter         wheel
apt                 hotshot             robotparser         whichdb
apt_inst            html5lib            runpy               wsgiref
apt_pkg             htmlentitydefs      runtime_err_survey  xdrlib
aptsources          htmllib             sched               xml
argparse            httplib             select              xmllib
array               ihooks              serializer          xmlrpclib
ast                 imaplib             sets                xxsubtype
asynchat            imghdr              setuptools          zipfile
asyncore            imp                 sgmllib             zipimport
atexit              importlib           sha                 zlib

Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".

BaseHTTPServer      audiodev            imputil             shlex
Bastion             audioop             indicator_keyboard  shutil
CDROM               base64              inspect             signal
CGIHTTPServer       bdb                 io                  signatures
Canvas              binascii            ipaddress           site
ConfigParser        binhex              itertools           sitecustomize
Cookie              bisect              json                six
Crypto              bottle              keyword             smtpd
DLFCN               bottle_server       lib2to3             smtplib
Dialog              bsddb               linecache           sndhdr
DocXMLRPCServer     bz2                 linuxaudiodev       socket
FileDialog          cPickle             locale              softwareproperties
FixTk               cProfile            logging             spwd
HTMLParser          cStringIO           lsb_release         sqlite3
IN                  cachecontrol        macpath             sre
LIVE_exec_js        caches              macurl2path         sre_compile
LIVE_exec_py2       calendar            mailbox             sre_constants
LIVE_exec_py3       cgi                 mailcap             sre_parse
MimeWriter          cgitb               markupbase          ssl
Queue               chardet             marshal             stat
ScrolledText        chunk               math                statvfs
SimpleDialog        cmath               md5                 string
SimpleHTTPServer    cmd                 mhlib               stringold
SimpleXMLRPCServer  code                mimetools           stringprep
SocketServer        codecs              mimetypes           strop
StringIO            codeop              mimify              struct
TYPES               collections         mmap                subprocess
Tix                 colorama            modulefinder        sunau
Tkconstants         colorsys            multifile           sunaudio
Tkdnd               command             multiprocessing     symbol
Tkinter             commands            mutex               symtable
UserDict            compileall          mysql               syntax_err_survey
UserList            compiler            netrc               sys
UserString          contextlib          new                 sysconfig
_LWPCookieJar       contrib             nis                 syslog
_MozillaCookieJar   cookielib           nntplib             tabnanny
__builtin__         copy                ntpath              talloc
__future__          copy_reg            nturl2path          tarfile
_abcoll             crypt               numbers             telnetlib
_ast                csv                 opcode              tempfile
_backport           ctypes              operator            termios
_bisect             curl                optparse            test
_bsddb              curses              os                  textwrap
_codecs             datetime            os2emxpath          this
_codecs_cn          dbhash              ossaudiodev         thread
_codecs_hk          dbm                 packages            threading
_codecs_iso2022     debconf             packaging           time
_codecs_jp          decimal             paramiko            timeit
_codecs_kr          difflib             parser              tkColorChooser
_codecs_tw          dircache            pdb                 tkCommonDialog
_collections        dis                 pexpect             tkFileDialog
_csv                distlib             pg_encoder          tkFont
_ctypes             distutils           pg_logger           tkMessageBox
_ctypes_test        doctest             pickle              tkSimpleDialog
_curses             doctest_exec        pickletools         toaiff
_curses_panel       doctest_reader      pip                 token
_elementtree        doctest_splitter    pipes               tokenize
_functools          dumbdbm             pkg_resources       tool
_hashlib            dummy_thread        pkgutil             trace
_heapq              dummy_threading     platform            traceback
_hotshot            easy_install        plistlib            treeadapters
_io                 ecdsa               popen2              treebuilders
_json               email               poplib              treewalkers
_locale             encodings           posix               trie
_lsprof             ensurepip           posixfile           ttk
_md5                errno               posixpath           tty
_multibytecodec     error_log           pprint              turtle
_multiprocessing    eureka_survey       profile             types
_osx_support        exceptions          progress            unicodedata
_pyio               extern              pstats              unittest
_random             fcntl               pty                 urllib
_sha                filecmp             ptyprocess          urllib2
_sha256             fileinput           pwd                 urllib3
_sha512             filters             py_compile          urlparse
_socket             fnmatch             pyclbr              user
_sqlite3            formatter           pycurl              util
_sre                fpectl              pydoc               uu
_ssl                fpformat            pydoc_data          uuid
_strptime           fractions           pyexpat             viz_interaction
_struct             ftplib              pyodbc              warnings
_symtable           functools           pyparsing           wave
_sysconfigdata      future_builtins     pysqlite2           weakref
_sysconfigdata_nd   gc                  quopri              web_exec_c
_testcapi           generate_json_trace random              web_exec_cpp
_threading_local    genericpath         re                  web_exec_java
_vendor             getopt              readline            web_exec_js
_warnings           getpass             repr                web_exec_py2
_weakref            gettext             requests            web_exec_py3
_weakrefset         glob                resource            web_exec_py3anaconda
abc                 grp                 retrying            web_exec_ruby
add_cache_busting_query_strings gzip                rexec               web_exec_ts
aifc                hashlib             rfc822              webbrowser
antigravity         heapq               rlcompleter         wheel
anydbm              hmac                robotparser         whichdb
apt                 hotshot             runpy               wsgiref
apt_inst            html5lib            runtime_err_survey  xdrlib
apt_pkg             htmlentitydefs      sched               xml
aptsources          htmllib             select              xmllib
argparse            httplib             serializer          xmlrpclib
array               ihooks              sets                xxsubtype
ast                 imaplib             setuptools          zipfile
asynchat            imghdr              sgmllib             zipimport
asyncore            imp                 sha                 zlib
atexit              importlib           shelve              

Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".

Note that there is possible your program are display different result. that is a way to display all available modules.

There is possible to check specified module within all class and method using dir() function. there is syntax as follows.


For example

import sys #import the module

# display sys available function, and class
['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe', '_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'set_coroutine_wrapper', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions']

Another example display functions in math modules.

import math
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

There is big advantage of python we can get information about all available modules and within its function. But only name of not sufficient to access any function. there are need more information such as number of parameter, value of parameter and default value of parameter, and its returning results. so we can also get specified module information using help() function. for example.

import math
help(math) #module name math

    This module is always available.  It provides access to the
    mathematical functions defined by the C standard.

        Return the arc cosine (measured in radians) of x.
        Return the inverse hyperbolic cosine of x.
        Return the arc sine (measured in radians) of x.
        Return the inverse hyperbolic sine of x.
        Return the arc tangent (measured in radians) of x.
        atan2(y, x)
        Return the arc tangent (measured in radians) of y/x.
        Unlike atan(y/x), the signs of both x and y are considered.
        Return the inverse hyperbolic tangent of x.
        Return the ceiling of x as an Integral.
        This is the smallest integer >= x.
        copysign(x, y)
        Return a float with the magnitude (absolute value) of x but the sign 
        of y. On platforms that support signed zeros, copysign(1.0, -0.0) 
        returns -1.0.
        Return the cosine of x (measured in radians).
        Return the hyperbolic cosine of x.
        Convert angle x from radians to degrees.
        Error function at x.
: more record

Similar way we can check or get information about any module.

And also possible to get the information about user defined function definition. let take this example.

import inspect #include module

# user defined function
# this function are accepted 4 parameters
# last two is take default value
def ourMethod(self, param1, param2=None,param3=9):
    return self
#provide function name to signature method
about = inspect.signature(ourMethod) 
print(about) #display a function definition
(self, param1, param2=None, param3=9)


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment