Organizing Code in Modules
Learn how to organize code in the form of modules.
We'll cover the following...
The Python module is an important focus. Every application or web service has at least one module. Even a seemingly “simple” Python script is a module. Inside any one module, we can specify variables, classes, or functions. They can be a handy way to store the global state without namespace conflicts.
Example
For example, we have been importing the Database
class into various modules and then instantiating it, but it might make more sense to have only one database
object globally available from
the database
module. The database
module might look like this:
class Database:"""The Database Implementation"""def __init__(self, connection: Optional[str] = None) -> None:"""Create a connection to a database."""passdatabase = Database("path/to/data")
Then we can use any of the import methods we’ve discussed to access the database
object, for example:
from ecommerce.database import database
Use of Optional
type hint
A drawback of the preceding class is that the database
object is created immediately when the module is first imported, which is usually when the program starts up. This isn’t always ideal, since connecting to a database can take a while, slowing down startup, or the database connection information may not yet be available because we need to read a configuration file. We could delay creating the database until it is actually needed by calling an initialize_database()
function to create a module-level variable:
db: Optional[Database] = None
def initialize_database(connection:
...