I believe that readability and the KISS principle are the most important things in programming. That's why I use Python :)
And here is exact situation, which I encounter very often:
Say, I have a nice and clean script, which is a wrapper for database handling:
import database_schema as schema
loader = schema.Loader("sqlite:///var/database.db")
session = loader.session
def addUser(name, full_name, password):
user = schema.User(name, full_name, password)
session.add(user)
session.commit()
def listUsers():
all_users = session.query(schema.User).all()
return all_users
Which is used like this:
import database
database.addUser("mike", "Mike Driscoll", "password")
database.listUsers()
At some point, I want to rewrite that module, so that it can work with databases on different path (for unit testing, for instance).
So, what are my options?
The most intuitive thing is to add
database_path == ""
variable, and then... what? Setting it withsetPath(new_path)
function, and then adding exception (if database_path == "": raise SomeException
) to every single function, is just ugly and shouldn't be done by anyone.Full featured class, with setting the
self._database_path
at initialization time.
Which is then used this way:
from database import Database
database = Database("sqlite:///var/database.db")
database.addUser("mike", "Mike Driscoll", "password")
database.listUsers()
This is already more lines of code than in the first example, and addition of the naming problem: having a class called Database
in the module database
is kind of dumb, no?
Sorry for the long read, here my final questions:
- Why there's no such thing as
__init__
functions for modules, in Python? - Am I missing something (static class variables, etc), that can do what I want (a constant set at the import time) the easy and clean way, that is still not far away from a module with a bunch of simple functions that was at first?
P.S. sorry for my English.
Edit:
So, to make this clear, how this code may look like in my imaginative Python universe:
import database_schema as schema
def __init__(database_path):
loader = schema.Loader(database_path)
global session
session = loader.session
def addUser(name, full_name, password):
user = schema.User(name, full_name, password)
session.add(user)
session.commit()
def listUsers():
all_users = session.query(schema.User).all()
return all_users
And used like this:
import database("sqlite:///var/database.db")
database.addUser("mike", "Mike Driscoll", "password")
database.listUsers()