[Tutor] function with multiple checks

Evert Rol evert.rol at gmail.com
Mon Sep 27 17:51:24 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.

set does seem to have what you want: isdisjoint() could do the trick.

    if set(punctuation).isdisjoint(password) or set(digits).isdisjoint(password) or set(ascii_uppercase).isdisjoint(password) or set(ascii_lowercase).isdisjoint(password):
         return False
    return True

You could even confuse yourself and put it all on one line:

      return not any(set(chars).isdisjoint(password) for chars in [punctuation, digits, ascii_uppercase, ascii_lowercase])

but I wouldn't recomended it. I guess this can even shortened further.
(note: the 'not' operator is needed, because isdisjoint returns True for what you probably prefer as False.)


> 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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list