Skip to content

Commit 2d05b9c

Browse files
committed
2.8.1 - added camel_to_snake function
1 parent 6ea47ca commit 2d05b9c

4 files changed

Lines changed: 32 additions & 1 deletion

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
camel\_to\_snake
2+
================
3+
4+
.. currentmodule:: privex.helpers.common
5+
6+
.. autofunction:: camel_to_snake

docs/source/helpers/privex.helpers.common.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ privex.helpers.common
1010

1111
byteify
1212
call_sys
13+
camel_to_snake
1314
chunked
1415
construct_dict
1516
dec_round

privex/helpers/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ def _setup_logging(level=logging.WARNING):
136136
log = _setup_logging()
137137
name = 'helpers'
138138

139-
VERSION = '2.8.0'
139+
VERSION = '2.8.1'
140140

141141

142142

privex/helpers/common.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -653,6 +653,30 @@ def error(self, message):
653653
sys.exit(2)
654654

655655

656+
first_cap_re = re.compile('(.)([A-Z][a-z]+)')
657+
all_cap_re = re.compile('([a-z0-9])([A-Z])')
658+
659+
660+
def camel_to_snake(name: STRBYTES) -> str:
661+
"""
662+
Convert ``name`` from camel case (``HelloWorld``) to snake case (``hello_world``).
663+
664+
``name`` can be either a ``str`` or ``bytes``.
665+
666+
Example::
667+
668+
>>> camel_to_snake("HelloWorldLoremIpsum")
669+
'hello_world_lorem_ipsum'
670+
671+
672+
:param str|bytes name: A camel case (class style) name, e.g. ``HelloWorld``
673+
:return str snake_case: ``name`` converted to snake case ``hello_world``
674+
"""
675+
676+
s1 = first_cap_re.sub(r'\1_\2', stringify(name))
677+
return all_cap_re.sub(r'\1_\2', s1).lower()
678+
679+
656680
def human_name(class_name: Union[str, bytes, callable, Type[object]]) -> str:
657681
"""
658682
This function converts a class/function name into a Title Case name. It also directly accepts classes/functions.

0 commit comments

Comments
 (0)