Example HTML page

Modules

In this section, i would like to describe how to create and import a module in python.

Defining module

A module is a file which consists of Python code. It organizes the python code logically. By grouping related code into a module makes the code to understand easily. A module can define functions, classes and variables including runnable code.

Creating module

To define a module, simply use your text editor to type some Python code into a text file, and save it with a “.py“ extension; any such file is automatically considered a Python module.

Importing module

We can import a module by using the following three statements.

  1. import statement
  2. The from…import statement
  3. The from…import* statement

1.import statement

To import a python module we use import statement and we can access the definitions inside it using the dot operator. We can import a module as shown in below:

>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe', '_home', '_mercurial', '_xoptions', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getwindowsversion', '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', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions', 'winver']

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. Following is a simple example:

>>> import os
>>> dir(os)
['F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_execvpe', '_exists', '_exit', '_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'write']

The following is an example that depicts how to import a module.

>>> import math

>>> import factorial

enter a number: 5

120

 Another way to import a module is by using any one of “.py” extension file. For instance I am using “factorial.py” file while importing a module.

number=int(input("enter a number:"))
factorial=1
for i in range(1,number+1):
    factorial=factorial*i
print(factorial)

When you execute the above code it produces the following output

enter a number: 5

120

Note: We can reload a module only once. If you try to re-import the same module it displays nothing.

>>> import factorial

enter a number: 5

120

>>> import factorial

>>>

2.The from…import statement

This statement allows you to import specific attributes from a module.

Syntax

from modname import name1[, name2[, … nameN]]

 Ex

>>> num_items=int(input("enter the number of items purchased:"))
item_list=[ ]
for i in range(1,num_items+1):
    item=int(input("enter the cost of item %d,"%i))
    item_list.append(item)
print(item_list)
sum=0
for x in item_list:
    sum=sum+x
print(sum)


>>> from purchase1 import item_list
enter the number of items purchased: 5
enter the cost of item 1, 10
enter the cost of item 2, 20
enter the cost of item 3, 30
enter the cost of item 4, 40
enter the cost of item 5, 50
[10, 20, 30, 40, 50]
150

If you observe the above example we are not importing an entire module but specific portion of that module is imported.

3. The from…import* statement:

If you want to import all the names from a module into the current namespace you use the following import statement.

from modname import *

This provides an easy way to import all the items from a module into the current namespace.

 

Example HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest