[Tutor] function with multiple checks

Tim Miller tim at lashni.net
Mon Sep 27 17:09:54 CEST 2010


I've got a small function that I'm using to check whether a password is 
of a certain length and contains mixed case, numbers and punctuation.

Originally I was using multiple "if re.search" for the patterns but it 
looked terrible so I've read up on list comprehensions and it's slightly 
improved. I just can't escape the feeling that there's a more elegant 
way to do this that I'm missing.

I've been looking through all the python stuff that I thought might be 
relevant (lambda, map, filter, set, frozenset, etc) but nothing has come 
together. Just wondering if anyone has suggested reading material for 
alternate ways they'd handle this code.

CODE:

from string import ascii_lowercase, ascii_uppercase, digits, punctuation


def complex_password(password):
     """Checks password for sufficient complexity."""
     if len(password) < 12:
         return False
     if len([c for c in password if c in punctuation]) == 0:
         return False
     if len([c for c in password if c in digits]) == 0:
         return False
     if len([c for c in password if c in ascii_uppercase]) == 0:
         return False
     if len([c for c in password if c in ascii_lowercase]) == 0:
         return False
     return True


More information about the Tutor mailing list