Contents
Modules and Packages
In the following post we will see what modules and Packages are and in python how Exception handling is taken care while programming.
Modules in Python are simply Python files with the .py extension, which implement a set of functions. Modules are imported from other modules using the import command. Before you go ahead and import modules, check out the full list of built-in modules in the Python Standard library.
When a module is loaded into a running script for the first time, it is initialized by executing the code in the module once. If another module in your code imports the same module again, it will not be loaded twice but once only – so local variables inside the module act as a “singleton” – they are initialized only once.
If we want to import module math, we simply import the module:
# import the library
import math
# use it (ceiling rounding)
math.ceil(2.4)
Exploring built-in modules
While exploring modules in Python, two important functions come in handy – the dir and help functions. dir functions show which functions are implemented in each module. Let us see the below example and understand better.
print(dir(math))
When we find the function in the module we want to use, we can read about it more using the help function, inside the Python interpreter:
help(math.ceil)
Writing modules
Writing Python modules is very simple. To create a module of your own, simply create a new .py file with the module name, and then import it using the Python file name (without the .py extension) using the import command.
Writing packages
Packages are name-spaces which contain multiple packages and modules themselves. They are simply directories, but with a twist.
The twist is, each package in Python is a directory which MUST contain a special file called **\__init\__.py**. This file can be empty, and it indicates that the directory it contains is a Python package, so it can be imported the same way a module can be imported.
If we create a directory called foo, which marks the package name, we can then create a module inside that package called bar. We also must not forget to add the **\__init\__.py** file inside the foo directory.
To use the module bar, we can import it in two ways:
# Just an example, this won't work
import foo.bar
# OR could do it this way
from foo import bar
In the first method, we must use the foo prefix whenever we access the module bar. In the second method, we don’t, because we import the module to our module’s name-space.
The **\__init\__.py** file can also decide which modules the package exports as the API, while keeping other modules internal, by overriding the **\__all\__** variable, like so:
__init__.py:
__all__ = ["bar"]
Errors and Exception Handling
In this section, we will learn about Errors and Exception Handling in Python. You’ve might have definitely encountered errors by this point in the course. For example:
f = open('test51.txt')
f.write("sdfsdsf")
5/0
print('Hello)
"suda"+6
Note how we get a SyntaxError, with the further description that it was an End of Line Error (EOL) while scanning the string literal. This is specific enough for us to see that we forgot a single quote at the end of the line. Understanding of these various error types will help you debug your code much faster.
This type of error and description is known as an Exception. Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal.
You can check out the full list of built-in exceptions [here](https://docs.python.org/2/library/exceptions.html). Now, let’s learn how to handle errors and exceptions in our own code.
f= open('test21.txt')
print(f.read())
f.write("my name is sudh")
print("this operation is correct")
b = int(input("insert your integer"))
a = 5/b
a
try and except
The basic terminology and syntax used to handle errors in Python is the **try** and **except** statements. The code which can cause an exception to occur is put in the *try* block and the handling of the exception are the implemented in the *except* block of code. The syntax form is:
try:
You do your operations here...
...
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
...
else:
If there is no exception then execute this block.
Using just except, we can check for any exception: To understand better let’s check out a sample code that opens and writes a file:
f = open(‘test21.txt’)
print(f.write(“DSfdsfsfds”))
try:
f = open(‘test21.txt’)
print(f.write(“DSfdsfsfds”))
except:
print( “this code is not correct “)
try :
c = int(input())
a = 6 + c
except:
print(“this is a nested try block “)
else :
try:
f = open('test21.txt')
print(f.write("DSfdsfsfds"))
except:
print( "this code is not correct ")
try :
c = int(input())
a = 6 + c
except:
print("this is a nested try block ")
else :
try:
b =int( input("input a int for this operation "))
c = 6/b
print(c)
except:
print("sorry i am able to execute this ")
else:
print("this will execute itself onece try will execute successfully")
finally:
print("this is my finally block it will execute itself in any condition")
try :
a = b+c
except:
After completing these codes, go through next lesson: Tkinter in python
1 thought on “Modules & Packages Exception handling”