Skip to content

Instantly share code, notes, and snippets.

@domodomodomo
Last active October 5, 2019 09:11
Show Gist options
  • Save domodomodomo/c518686140211276ff5d8fb234af33ab to your computer and use it in GitHub Desktop.
Save domodomodomo/c518686140211276ff5d8fb234af33ab to your computer and use it in GitHub Desktop.
Convert Python attributes from snake case to lower camel case. This gist might be useful when you use an application supporting GraphQL like Ariadne and Graphene.
def snake_to_kebab(identifier):
if isinstance(identifier, list):
container = range(len(identifier))
for element in container:
snake_to_kebab(identifier[element])
elif isinstance(identifier, dict):
container = [key for key in dict.keys()]
for element in container:
snake_to_kebab(getattr(identifier, element))
#
if _is_snake(element):
_set_kebab(identifier, element)
elif hasattr(identifier, "__dict__"):
# attr except private or protected
container = [attr for attr in identifier.__dict__.keys() if attr[0] != "_"]
for element in container:
snake_to_kebab(getattr(identifier, element))
#
if _is_snake(element):
_set_kebab(identifier, element)
def _is_snake(attr):
words = attr.split("_")
# private or protected attribute.
# like... _attr, __attr
if attr[0] == "_":
return False
elif len(words) == 1:
return False
# PEP 8 conventional
# list_, str_
elif len(words) == 2 and words[-1] == "":
return False
else:
return True
def _set_kebab(identifier, element):
snake = element
kebab = _snake_to_kebab(element)
setattr(identifier, kebab, getattr(identifier, snake))
delattr(identifier, snake)
def _snake_to_kebab(attr):
upper_kebab_case = "".join(x.capitalize() for x in attr.split("_"))
lower_kebab_case = upper_kebab_case[0].lower() + upper_kebab_case[1:]
return lower_kebab_case
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment