Skip to main content
In this lesson, we focus on streamlining our main.py file by removing redundant imports and outdated code snippets. With the migration of our routes to designated folders and the adoption of SQLAlchemy for database interactions, many of the previously used imports are now obsolete. Below, we outline the changes made and provide detailed examples for better clarity. Many unused imports appear grayed out in your IDE. For example, consider the following block of code that once included multiple imports and a raw database connection:
The code for connecting to the database using the traditional Postgres driver is now redundant because SQLAlchemy is managing our database connections. It is recommended to either move this logic into the database.py file for future reference or remove it completely.
For documentation purposes, here is how the section originally looked before the changes were implemented:
Since SQLAlchemy now handles our database operations, the raw SQL connection is obsolete and can be safely deleted from the main.py file. Only the necessary functions and modules from the database module need to be imported. Next, we remove additional unused imports and helper functions. Earlier versions of main.py included elements from typing, status, Body, Pydantic, and even the Postgres library, which are no longer utilized after integrating the database. For example, the following code block demonstrated older implementations that are now redundant:
Additionally, helper functions like the ones below have become unnecessary:
Removing these unused sections not only makes your main.py file cleaner but also improves maintainability by reducing clutter. The focus is now solely on the application’s main functionality.
The final cleaned-up version of main.py is structured more succinctly. It now only imports the modules required for the proper functioning of the application and includes the essential routers. The refined file is as follows:
With these changes, the application is free from redundant code and unused imports, making it easier to maintain and enhancing overall code clarity. This optimization is key for better project scalability and improved performance.

Watch Video