Last active
December 9, 2023 05:41
-
-
Save csm10495/e0d80087bfc663f86e20c5f533861e07 to your computer and use it in GitHub Desktop.
snakeify_sample.py - Sample code to convert logging to have snake-case aliases.
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
''' | |
Sample code to convert a module on import to snake_case from camelCase. | |
I wouldn't use this in production, but its kind of interesting to play with. | |
(C) 2023 - MIT License - Charles Machalow | |
''' | |
import inflection # pip install inflection | |
import inspect | |
import importlib | |
from typing import Any | |
def to_underscore(thang: Any): | |
dir_thang = dir(thang) | |
for name in dir_thang: | |
if not name.startswith('_'): | |
thing = getattr(thang, name) | |
if hasattr(thing, '__mro__'): | |
# a class | |
if inflection.underscore(name) not in dir(thing): | |
setattr(thang, name, to_underscore(thing)) | |
elif inspect.isfunction(thing): | |
# a function | |
if inflection.underscore(name) != name: | |
if inflection.underscore(name) not in dir_thang: | |
# print(f"{thing}.{name} -> {inflection.underscore(name)}") | |
setattr(thang, inflection.underscore(name), thing) | |
# todo: could add support for instances, other modules, etc. | |
return thang | |
def snakeify(mod: str): | |
module = importlib.import_module(mod) | |
return to_underscore(module) | |
if __name__ == '__main__': | |
logging = snakeify('logging') | |
log = logging.get_logger(__name__) | |
log.set_level(logging.DEBUG) | |
sh = logging.StreamHandler() | |
sh.set_level(logging.DEBUG) | |
sh.set_formatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) | |
log.add_handler(sh) | |
log.info('hi') |
Please don't call this "pep8ify". It does not create compliance with PEP 8. What it creates is snake_case_names. This is very different, and the current name is misleading in a way that perpetuates dangerous misinformation.
Done. Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please don't call this "pep8ify". It does not create compliance with PEP 8. What it creates is snake_case_names. This is very different, and the current name is misleading in a way that perpetuates dangerous misinformation.