ActiveState Code

Recipe 576905: A nicer password container than str


Because I did not want to expose my passwords in plain text whenever an exception was thrown or inside the debugger, I made this very small snippet. It's very simple, but I think it can be quite useful...

Python
1
2
3
class passwd(str):
	def __repr__(self):
		repr('*' * self.__len__())

Discussion

If you want to use the password, you can use e.q.:

>>> astr = 'aString'
>>> astr
'aString'
>>> print astr
aString
>>> apwd = passwd('aPassword')
>>> apwd
'*********'
>>> print apwd
aPassword

but it will not immediately show up in your debugger in plain text or in exception frames as __repr__ is used in those scenarios.

Comments

  1. 1. At 6:11 p.m. on 15 sep 2009, Gabriel Genellina said:

    Nice! Although I'd write it as:

    class passwd(str):
        def __repr__(self):
            return repr('*' * len(self))
    
  2. 2. At 1:45 a.m. on 16 sep 2009, david.gaarenstroom (the author) said:

    Yep, that's a better version. I'll be using that one myself from now on... Thanks!

  3. 3. At 12:42 p.m. on 13 nov 2009, niklas a said:

    I like the simplicity of the code. Very useful. However I don't see why you have to reveal the length of your password. Why not use 8 * '*' for example.

Sign in to comment