Module
Till now we discussed about
the Function, but at times we may require the Function defined in an
Application to be used in another one. One way, is to redefine the Function
once again at the required place. The other way is , to save the function as a
Module and include it any Application in which it is required.
What is a Module?
The Module is nothing but a
File where one or more related Functions and also Classes are defined. It is
considered as Library file, which can be included in any Application.
Again like in Functions,
Modules can also be of 2 types System Defined and User Defined.
The module has to be
imported into the current program before using it. To import a Module use the
following syntax,
Syntax
import
<module name>
Once the module is successfully imported we can use the
function. But at times, a same Function name may be available in 2 or more
modules. The better programming practice is to use the Function name along with
Module name to avoid any ambiguity.
Characteristics of
Module
]The module can have
any number of Functions defined within it.
]Along with the
Functions even Classes, Constants can also be defined in it.
]Each Function or
class or Constants can be referred separately whenever required.
]It is not
necessary to use all the Functions within the Module.
]This is
applicable to both User defined and System defined Modules
]Few functions
like input(), print(), type() are available without importing any module, these
are Built in Functions that comes along with the language itself.
When Python environment is
loaded few default modules are also loaded, which we need not import
explicitly. These functions are available in "builtins" module. To
view the Functions available in builtins, the procedure is , in the Interpreter
prompt of Python type.
import
builtins
and press enter, then type
dir(builtins)
this will list out the names
of the default functions , methods, constants and classes available in the
module "builtins". To know the syntax of any function under a module
use HELP function. In the interpreter type,
help
(<function name>)
Example
>>> help(object)
Help on class object in module __builtin__:
class object
| The most base type
eg. help(print). To list out the System defined Modules available, in
the interpreter tupe
>>> help("modules")
Please wait a
moment while I gather a list of all available modules...
AutoComplete _sqlite3 hashlib riding
AutoCompleteWindow _sre heapq rith
AutoExpand _ssl hello rithish
BankAccount _strptime hi rithishkumar
BaseHTTPServer _struct hmac rk
Bastion _subprocess hotshot rlcompleter
Bindings _symtable htmlentitydefs robotparser
CGIHTTPServer _testcapi htmllib rpc
CSC _threading_local httplib rs
CallTipWindow _tkinter idle rss
CallTips _warnings idlelib rsss
Canvas _weakref idlever rssss
ClassBrowser _weakrefset if run
CodeContext _winreg ifelseif runpy
ColorDelegator abc ihooks sample
ConfigParser aboutDialog imageop sched
Cookie aifc imaplib select
Danusrii amount imghdr sets
Debugger antigravity imp sgmllib
Delegator anuuuuuuuu importlib sha
Dialog anuuuuuuuuuuuuuuuu imputil shelve
DocXMLRPCServer anydbm inspect shlex
EditorWindow argparse io shutil
Enter array ish signal
FileDialog ast itertools site
FileList asynchat jj smtpd
FixTk asyncore jojo smtplib
FormatParagraph atexit json sndhdr
GrepDialog audiodev keybindingDialog socket
HTMLParser audioop keyword sql
HyperParser base64 kum sqlite3
IOBinding bdb kumar squares
IdleHistory binascii kutti sre
MimeWriter binhex lib2to3 sre_compile
MultiCall bisect linecache sre_constants
MultiStatusBar break listttt sre_parse
ObjectBrowser bsddb locale ssl
OutputWindow bye logging stat
ParenMatch bz2 macosxSupport statvfs
PathBrowser cPickle macpath string
Percolator cProfile macurl2path stringold
PyParse cStringIO mailbox stringprep
PyShell calendar mailcap strop
Queue cgi markupbase struct
RemoteDebugger cgitb marshal student
RemoteObjectBrowser
chunk math subprocess
ReplaceDialog cmath md5 sunau
RstripExtension cmd membership sunaudio
ScriptBinding code mhlib symbol
ScrolledList codecs mimetools symtable
ScrolledText codeop mimetypes synchronizing
SearchDialog collections mimify sys
SearchDialogBase colorsys mmap sysconfig
SearchEngine commands mmm t
SimpleDialog compileall modulefinder tabbedpages
SimpleHTTPServer compiler msilib tabnanny
SimpleXMLRPCServer configDialog msvcrt tarfile
SocketServer configHandler multifile telnetlib
StackViewer configHelpSourceEdit multilevel
inheri tempfile
StringIO configSectionNameDialog
multiprocessing test
Tix contextlib multithread testcode
Tkconstants continue mutex textView
Tkdnd cookielib naveen textwrap
Tkinter copy nestedif thalapathi
ToolTip copy_reg netrc this
TreeWidget csv new thread
UndoDelegator ctypes nnnkkk threading
UserDict curses nntplib threadmodule
UserList data nt time
UserString datetime ntpath timeit
WidgetRedirector dbhash nturl2path tkColorChooser
WindowList decimal numbers tkCommonDialog
ZoomHeight dh oneg tkFileDialog
_LWPCookieJar difflib op tkFont
_MozillaCookieJar dircache opcode tkMessageBox
__builtin__ dis operator tkSimpleDialog
__future__ distutils operator overloading toaiff
_abcoll doctest optparse token
_ast dumbdbm os tokenize
_bisect dummy_thread os2emxpath tony
_bsddb dummy_threading p trace
_codecs dynOptionMenuWidget parser traceback
_codecs_cn email pdb ttk
_codecs_hk employee pickle tty
_codecs_iso2022 encodings pickletools turtle
_codecs_jp errno pipes types
_codecs_kr example1 pkgutil unicodedata
_codecs_tw exceptions platform unittest
_collections fgg plistlib urllib
_csv fhgj pocm urllib2
_ctypes filecmp pocm1 urlparse
_ctypes_test fileinput pocm2 user
_elementtree fnmatch popen2 uu
_functools fo poplib uuid
_hashlib fooorrrr posixfile warnings
_heapq formatter posixpath wave
_hotshot fpformat pprint weakref
_io fractions profile webbrowser
_json ftplib pstats whichdb
_locale fun pty winsound
_lsprof functools py_compile wsgiref
_md5 future_builtins pyclbr xdrlib
_msi gc pydoc xml
_multibytecodec genericpath pydoc_data xmllib
_multiprocessing getopt pyexpat xmlrpclib
_osx_support getpass quopri xxsubtype
_pyio gettext r zipfile
_random gg random zipimport
_sha glob re zlib
_sha256 greatesvalue repr
_sha512 gzip rexec
_socket h rfc822
Enter any
module name to get more help. Or, type
"modules spam" to search
for modules
whose descriptions contain the word "spam".
>>>
we will get a display of
Module Names in alphabetical order. While the DIR function lists out the
Functions available in the loaded Module. The HELP function lists out the
Syntax of a particular Function
Packages
While Modules are equivalent
to Files in a System, The Packages are equivalent to Folders. Therefore
referring any Function that is available in a Package, will be like
<package
name>.<module name>.<function name>
Using FROM
statement
To avoid writing such
lengthy part of Package, Module and Function name each time , we can use the
From statement.
Syntax
from <Module name> import <function
name>
If only a particular
function is going to be used within our program, then we can just use
import < Module name >.<function name>
Both helps to refer a
Function without referring the Module names or Package Names during usage. Just
reference of Function name is enough, when a Module is imported. But good
programming practice is to include the Module name also to avoid any clash of
same Function names in different Modules are already discussed.
Using alias name for /modules in Import Statement
Instead of using the lengthy
module name. function name each time we refer, it is possible to use Alias
where we can replace the modulename.functionname with the aliasname.
Syntax
import <module name> as <alias name>
Example
import module1 as M
Whenever we have to refer
the Module1,we can use the alias M instead. This is even applicable to the
Functions within the module.
No comments:
Post a Comment