diff --git a/changes/3463-schlerp.md b/changes/3463-schlerp.md new file mode 100644 index 0000000..bb1fb75 --- /dev/null +++ b/changes/3463-schlerp.md @@ -0,0 +1 @@ +created new function `to_lower_camel()` for "non pascal case" camel case. diff --git a/docs/usage/model_config.md b/docs/usage/model_config.md index b6c15e0..8f05fa3 100644 --- a/docs/usage/model_config.md +++ b/docs/usage/model_config.md @@ -143,7 +143,7 @@ _(This script is complete, it should run "as is")_ Here camel case refers to ["upper camel case"](https://en.wikipedia.org/wiki/Camel_case) aka pascal case e.g. `CamelCase`. If you'd like instead to use lower camel case e.g. `camelCase`, -it should be trivial to modify the `to_camel` function above. +instead use the `to_lower_camel` function. ## Alias Precedence diff --git a/pydantic/utils.py b/pydantic/utils.py index 8588625..972f2e2 100644 --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -303,6 +303,13 @@ def to_camel(string: str) -> str: return ''.join(word.capitalize() for word in string.split('_')) +def to_lower_camel(string: str) -> str: + if len(string) >= 1: + pascal_string = to_camel(string) + return pascal_string[0].lower() + pascal_string[1:] + return string.lower() + + T = TypeVar('T') diff --git a/tests/test_utils.py b/tests/test_utils.py index d7eaa74..eb7caa9 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -37,6 +37,7 @@ from pydantic.utils import ( lenient_issubclass, path_type, smart_deepcopy, + to_lower_camel, truncate, unique_list, ) @@ -528,6 +529,18 @@ def test_undefined_pickle(): assert undefined2 is Undefined +def test_on_lower_camel_zero_length(): + assert to_lower_camel('') == '' + + +def test_on_lower_camel_one_length(): + assert to_lower_camel('a') == 'a' + + +def test_on_lower_camel_many_length(): + assert to_lower_camel('i_like_turtles') == 'iLikeTurtles' + + def test_limited_dict(): d = LimitedDict(10) d[1] = '1'