MCPcopy Index your code
hub / github.com/danielgtaylor/python-betterproto / snake_case

Function snake_case

src/betterproto/casing.py:25–63  ·  view source on GitHub ↗

Join words with an underscore into lowercase and remove symbols. Parameters ----------- value: :class:`str` The value to convert. strict: :class:`bool` Whether or not to force single underscores. Returns -------- :class:`str` The value in sn

(value: str, strict: bool = True)

Source from the content-addressed store, hash-verified

23
24
25def snake_case(value: str, strict: bool = True) -> str:
26 """
27 Join words with an underscore into lowercase and remove symbols.
28
29 Parameters
30 -----------
31 value: :class:`str`
32 The value to convert.
33 strict: :class:`bool`
34 Whether or not to force single underscores.
35
36 Returns
37 --------
38 :class:`str`
39 The value in snake_case.
40 """
41
42 def substitute_word(symbols: str, word: str, is_start: bool) -> str:
43 if not word:
44 return ""
45 if strict:
46 delimiter_count = 0 if is_start else 1 # Single underscore if strict.
47 elif is_start:
48 delimiter_count = len(symbols)
49 elif word.isupper() or word.islower():
50 delimiter_count = max(
51 1, len(symbols)
52 ) # Preserve all delimiters if not strict.
53 else:
54 delimiter_count = len(symbols) + 1 # Extra underscore for leading capital.
55
56 return ("_" * delimiter_count) + word.lower()
57
58 snake = re.sub(
59 f"(^)?({SYMBOLS})({WORD_UPPER}|{WORD})",
60 lambda groups: substitute_word(groups[2], groups[3], groups[1] is not None),
61 value,
62 )
63 return snake
64
65
66def pascal_case(value: str, strict: bool = True) -> str:

Callers 3

test_snake_case_strictFunction · 0.90
safe_snake_caseFunction · 0.85

Calls 1

substitute_wordFunction · 0.85

Tested by 2

test_snake_case_strictFunction · 0.72