Skip to content

Instantly share code, notes, and snippets.

@averykhoo
Last active November 22, 2021 06:46
Show Gist options
  • Save averykhoo/2090668eed89f4d254b4253481cfa543 to your computer and use it in GitHub Desktop.
Save averykhoo/2090668eed89f4d254b4253481cfa543 to your computer and use it in GitHub Desktop.
get module, class, function name
import inspect
from functools import lru_cache
from functools import partial
from typing import Callable
@lru_cache(maxsize=None)
def get_function_name(func: Callable) -> str:
"""
Get the name of a function.
"""
# un-partial if needed
while isinstance(func, partial):
func = func.func
# get class if it's a bound method
cls = None
# noinspection PyUnresolvedReferences
if inspect.ismethod(func) or (inspect.isbuiltin(func) and
hasattr(func, '__self__') and
getattr(func.__self__, '__class__', None) is not None):
for _cls in inspect.getmro(func.__self__.__class__):
if func.__name__ in _cls.__dict__:
cls = _cls
break
# unbound method
elif inspect.isfunction(func):
_cls = getattr(inspect.getmodule(func), func.__qualname__.split('.<locals>')[0].rsplit('.', 1)[0], None)
if isinstance(_cls, type):
cls = _cls
# not a bound method, so there's probably no class, but we can check just in case
if cls is None:
cls = getattr(func, '__objclass__', None)
# get the function name
module = inspect.getmodule(func)
if cls is not None:
return f'<{module.__name__}>.{cls.__name__}.{func.__name__}'
else:
return f'<{module.__name__}>.{func.__name__}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment