Fix the snake_case helper that replaces an inline copy
Your task
An AI agent added an inline to_snake helper to your Python service and used it in three endpoints. It split at every capital letter, so HTTPStatus became h_t_t_p_status, and the service already had a casing helper the agent never looked for. You are replacing both with one canonical helper that understands acronyms.
An assistant wrote to_snake_case(name). It is in the editor. It has a bug. Find it and fix it.
Input and output:
name: an identifier in any casing style.- Return it in snake_case: lowercase words joined by
_.
Rules the tests check:
_,-and a space are separators. Each one becomes_.- Write each uppercase ASCII letter A to Z in lowercase. If it is not the first character, put a
_before it when either of these holds:- the character before it is a lowercase ASCII letter or a digit 0 to 9
- the character before it is an uppercase ASCII letter, and the character after it is a lowercase ASCII letter. This way the last capital of an acronym starts the next word.
- Every other character is copied as it is.
- Finally, collapse every run of
_into a single_, and remove any_at the start or the end.
Examples
to_snake_case(name: str) -> strExample 1
Input
to_snake_case("HTTPStatus")Output
"http_status"Example 2
Input
to_snake_case("getHTTPResponseCode")Output
"get_http_response_code"Example 3
Input
to_snake_case("already_snake")Output
"already_snake"