TheAlgorithms/Python · error · TypeError

Plugboard setting isn't type string ({type(pbstring)})

Error message

Plugboard setting isn't type string ({type(pbstring)})

What it means

Raised by _plugboard() in ciphers/enigma_machine2.py when the plugboard setting is not a str. The plugboard is described as a string of letter pairs (e.g. 'PICTURES'), so passing a dict, list, bytes, or None triggers this TypeError.

Source

Thrown at ciphers/enigma_machine2.py:136

    >>> _plugboard('PICTURES')
    {'P': 'I', 'I': 'P', 'C': 'T', 'T': 'C', 'U': 'R', 'R': 'U', 'E': 'S', 'S': 'E'}
    >>> _plugboard('POLAND')
    {'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'}

    In the code, ``pb`` stands for ``plugboard``

    Pairs can be separated by spaces

    :param pbstring: string containing plugboard setting for the Enigma machine
    :return: dictionary containing converted pairs
    """

    # tests the input string if it
    # a) is type string
    # b) has even length (so pairs can be made)
    if not isinstance(pbstring, str):
        msg = f"Plugboard setting isn't type string ({type(pbstring)})"
        raise TypeError(msg)
    elif len(pbstring) % 2 != 0:
        msg = f"Odd number of symbols ({len(pbstring)})"
        raise Exception(msg)
    elif pbstring == "":
        return {}

    pbstring.replace(" ", "")

    # Checks if all characters are unique
    tmppbl = set()
    for i in pbstring:
        if i not in abc:
            msg = f"'{i}' not in list of symbols"
            raise Exception(msg)
        elif i in tmppbl:
            msg = f"Duplicate symbol ({i})"
            raise Exception(msg)
        else:

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass a string of pairs: _plugboard('PICTURES') or the public API with pb='PICTURES'
  2. Convert a dict of pairs back to a string: ''.join(k + v for k, v in pairs.items())
  3. Use '' for 'no plugboard'

Example fix

# before
pb = {'P': 'O', 'L': 'A'}
_plugboard(pb)

# after
pb = 'POLA'
_plugboard(pb)
Defensive patterns

Strategy: type-guard

Validate before calling

if not isinstance(pb, str):
    pb = ''.join(k + v for k, v in pb.items()) if isinstance(pb, dict) else str(pb)

Type guard

def is_plugboard_string(value) -> bool:
    return isinstance(value, str)

Try / catch

try:
    pbdict = _plugboard(pb)
except TypeError as exc:
    if "isn't type string" in str(exc):
        pbdict = _plugboard('')  # no plugboard
    else:
        raise

Prevention

When it happens

Trigger: _plugboard({'P': 'O'}) with a dict; passing a list ['PI','CT','UR','ES']; passing None when no plugboard was configured; passing bytes.

Common situations: Naturally modelling the plugboard as a dict in calling code and passing it directly; optional settings defaulting to None; data arriving from JSON as a list of pairs.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/5ef8a4b532e4b7ea. Report an issue: GitHub.