> Articles > Writing a Python Library
In this article, we will explain writing a Python library.
Library is a collection of functionality in form of code which can be reused.
Library is a collection of functionality in form of code which can be reused. So we have some common code to provide functionality. We can come up with Library to have that code and that code can be reused in application to provide the functionality. Let's see how writing a python library is done.
Here are the steps for implementing the library.
Step 1-
Write the classes and methods in a python file.
Step 2-
Have the statement if __name__ == '__main__' at the end.
1. Import the library file which has classes and methods to be used.
2. Use the library file name to access the classes of the library.
3. Have both the files in same directory or environment variable PYTHONPATH set to library file path if its in different
directory.
Create a library for operation to do the operations backup, restore and update.
This is the way library will be used-
import Operationlib
...................
oprObject = Operationlib.Operation()
...................
We will write code of library in a python file. All the classes and methods of library will be in this file. These classes and methods will be reused by developer for their application.
At the end of the file we will have if statement if __name__ == '__main__'. This is really good feature of python. The statements under this condition will be executed when this python file is executed standalone, otherwise this file is used as module. So the file can be used as standalone application or library.
Now the library Operationlib is available which can be used in user file.
Operationlib.pyWe have the classes and methods of library and we want to use them. The developer will reuse the library classes and methods using library file name.
OperationlibDemo.pyNow we can place the library file and user file in same directory. Then we can run the user file.
If we want to have the library file in different directory. Then we have to set the library file path to environment
variable PYTHONPATH. Then we can run the user file. In this case any other user file from other directories can also use the
library file.