Python overloading

I think when one firsts looks at Python it appears not to be able to do operator overloading, this is not the case. You can overload a great deal of operators like +, in, = and function calls (). In my case I had the following problem.
For a while I've been using a file I call config.py which has a global variable that looks a little like this:
curDatabase = 'testdb'
g_databases = {
'testdb' : {
'desc' : 'Test Database',
'aTSN' : 'testdb.world',
'user' : 'ausername',
'password' : 'apassword',
...
},
...
}
I have a bunch of little programs which use this information to login to database, to VNC, to HTTP (JBoss) and FTP. The idea is that I don't have to remember password just the name that I gave the machine ("testdb" in this case). But having these passwords unencripted on my machine doesn't make me feel very safe.
I decided that the right thing to do is to use something like PasswordSafe to save the passwords and write a wrapper using the PyPwSafe library. What is nead is that before the client code was accessing the dictionary directly, now I've made a class which behaves just like a dict so the client code doesn't even realize that a change has been made. In addition I made the code lazy evaluate so that it wouldn't ask for the master password into pwsafe until the last possible moment.
Basically, I had to overload the methods:
def __contains__(self, key):
def __getitem__(self, key):
def __len__(self):
With these overloads and defining g_database = MyConfig() i can do g_databases['testdb']['user'], for example. The problem which my original code was that I was using a base data type directly, the nice thing with Python I can replace that with a class that behaves in the same way without having to change any of the code that uses it. This is called Duck Typing - if it walks like a duck and talks like a duck, then it might as well be a duck.

Technorati Tags:

Technorati Tags:

Comments

Popular posts from this blog

Shortest Sudoku solver in Python

Seven Segment Display in Inkscape