Solved

KeyError when reading a key that may not exist

ElaKowalskaOP

My config dict sometimes lacks "timeout" and config["timeout"] crashes.

9

Comments 5

Join the discussion

Already have an account? Log in

  1. AmeliaRuns Solutionreplies: 1

    Use .get() with a default:

    timeout = config.get("timeout", 30)

    It returns the default instead of raising KeyError.

    8
    1. OllieGrantreplies: 1

      Or check first: if "timeout" in config:. .get() is usually shorter.

      0
      1. NoahLoops

        Careful when 0 or "" is a valid value and you write config.get("timeout") or 30 — that replaces 0 with 30. .get("timeout", 30) doesn't have that problem.

        3