Skip to content

Instantly share code, notes, and snippets.

@csm10495
Last active December 9, 2023 05:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save csm10495/e0d80087bfc663f86e20c5f533861e07 to your computer and use it in GitHub Desktop.
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.
'''
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')
@Rosuav
Copy link

Rosuav commented Dec 7, 2023

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.

@csm10495
Copy link
Author

csm10495 commented Dec 9, 2023

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