Created
November 18, 2020 17:43
-
-
Save dumptruckman/4fa81c8a0ab9ecdcdec8cff3b6b7e394 to your computer and use it in GitHub Desktop.
Python class decorator for accessing lowerCamelCase attributes using snake_case.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Any | |
def snake_to_camel(name): | |
components = name.split('_') | |
return components[0] + ''.join(x.title() for x in components[1:]) | |
def snake_case_attrs(klass): | |
"""A class decorator that enables getting and setting of attributes with lowerCamelCase names using snake_case.""" | |
def __getattribute__(self, name: str) -> Any: | |
try: | |
return super(klass, self).__getattribute__(name) | |
except AttributeError: | |
return super(klass, self).__getattribute__(snake_to_camel(name)) | |
def __getattr__(self, name: str) -> Any: | |
return super(klass, self).__getattribute__(name) | |
def __setattr__(self, name: str, value: Any) -> None: | |
camel_name = snake_to_camel(name) | |
try: | |
getattr(self, camel_name) | |
super(klass, self).__setattr__(camel_name, value) | |
except AttributeError: | |
super(klass, self).__setattr__(name, value) | |
klass.__getattribute__ = __getattribute__ | |
klass.__getattr__ = __getattr__ | |
klass.__setattr__ = __setattr__ | |
return klass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment