Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple Python password creator
from itertools import cycle
from random import choice, shuffle
from string import ascii_lowercase, ascii_uppercase, digits, punctuation
def generate_password(length: int = 20, *, use_symbols: bool = True) -> str:
"""Generate random passwords, with or without symbols.
Implementation ensures a fairly even balance of each character
class, at the cost of entropy (e.g. for a four-character password
with symbols there are only 5,191,680 possible combinations, rather
than 78,074,896).
>>> from random import seed
>>> seed(0)
>>> generate_password()
>>> generate_password(use_symbols=True)
>>> generate_password(use_symbols=False)
>>> generate_password(10)
>>> generate_password(10, use_symbols=True)
>>> generate_password(10, use_symbols=False)
>>> generate_password(0)
>>> generate_password(-1)
>>> generate_password("foo")
Traceback (most recent call last):
TypeError: 'str' object cannot be interpreted as an integer
cases = [ascii_lowercase, ascii_uppercase, digits]
if use_symbols:
characters = [
for _, case
in zip(range(length), cycle(cases))
return "".join(characters)
if __name__ == "__main__":
import doctest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment