Python Classroom Series – 26/Aug/2020

Dummy Library Project

  • We are supposed to develop the Library in Python

  • This project will be used by librarian, faculty, students

  • As of now Library has

    • Books
    • Magazines
    • DVD’s
    • E-books
  • You have to implement the functionality to support the whole library activities

  • To implement this kind of project we might need to deal with lot of objects.

  • We would be defining/writing the code in multiple py files

  • So how should i organize the multiple py files

  • Modules are simply python files. so each python file is a module

  • So to develop the library application i will end up creating multiple modules

Lets look at multi module demo

  • Lets create a new folder moduledemo and in that create two python files app.py and database.py
  • Each file is a module. so in database.py add the following code
class Database:
    def __init__(self):
        pass

    def connect(self):
        pass

    def disconnect(self):
        pass


  • Now in app.py i want to create a database connection, so we need to create a object and then call method.
  • To use Class Database in app.py we need to import modules. Importing modules in python can be done by import statement
  • Using import statement i can import module or specific classes or functions from module.
  • Importing complete module
import database

db = database.Database()
db.connect()
  • importing specific class
from database import Database

db = Database()
db.connect()
db.disconnect()
  • Now lets create one more module called as utils.py
class DbUtils:
    pass

class FileUtils:
    pass

class HttpUtils:
    pass

  • Now lets assume if app.py module wants FileUtils and HttpUtils
from utils import FileUtils, HttpUtils

# instantiating Objects of FileUtils
file_utils = FileUtils()

# instantiating Objects of HttpUtils
http_utils = HttpUtils()
  • Some sources say that we will be importing all the classes and functions from the module using this syntax (Don’t do this)
from utils import *
  • As number of modules grow it would be logical to organize modules in some folders based on usage
  • A package is a collection of modules in a folder. The name of the package is name of folder
  • Lets create three packages called as
    • common
    • utilities
    • models Preview
  • The package will be shown in pycharm as Preview
  • We need to tell python that folder is a package to distinguish it from other folders. To do this we would be a file in the folder __init__.py
  • This file can be empty. If we forget this file, we wont be able to import modules from that folder.
  • So now lets create some modules in package common
  • Absolute imports specify the complete path to the module, function or class we want to import Preview
  • Refer to todays class at the following location

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin