aboutsummaryrefslogtreecommitdiff
path: root/alphanum/alphanum.py
blob: bb23cf5223836cddbc01d016040c22bf7ea451c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import random
import secrets
import string

POP = string.ascii_letters + string.digits


def generate(length: int = 1) -> str:
    """Generates a pseudo-random string of alphanumeric characters of the given
    length. If no length is specified, a single character is returned.

    Args:
        length (:obj:`int`, optional): Desired string length. Defaults to 1.

    Returns:
        str: A pseudo-random alphanumeric string.

    Examples:
        >>> print(alphanum.generate())
        'G'
        >>> print(alphanum.generate(10))
        'a93jfDjdA0'

    """
    return ''.join(random.SystemRandom().choices(POP, k=length))


def generate_s(length: int = 1) -> str:
    """Generates a cryptographically strong random string of alphanumeric
    characters of the given length. If no length is specified, a single
    character is returned.

    Args:
        length (:obj:`int`, optional): Desired string length. Defaults to 1.

    Returns:
        str: A random alphanumeric string.

    Examples:
        >>> print(alphanum.generate_s())
        '5'
        >>> print(alphanum.generate_s(10))
        't3g0Gh9Naj'

    """
    return ''.join(secrets.SystemRandom().choice(POP) for i in range(length))