In a utility function displaying both the argument and values of a calling function, I need to know the original name of an possibly aliased function imported from another module. Is this possibly for the simple case when aliasing on import?
Here is a simplified use case, where I first present some code from the utilities.py
module:
import inspect
DEBUG_FLAG = True
def _log_args(*args):
"""Uses reflection to returning passing argument code with values."""
prev_frame = inspect.currentframe().f_back
func_name = prev_frame.f_code.co_name
code_context = inspect.getframeinfo(prev_frame.f_back).code_context[0].strip()
# Do some magic, which does work _unless_ func_name is aliased :-)
print('code context: {}'.format(code_context))
print('func_name : {}'.format(func_name))
return ', '.join(str(arg) for arg in args)
def format_args(*args):
"""Returns string with name of arguments with values."""
return _log_args(args)
def debug_print(*args):
"""Prints name of arguments with values."""
if DEBUG_FLAG:
print _log_args(args)
And here is some code accessing these functions first by original name, and then by the aliases:
from utilities import debug_print, format_args, debug_print as debug, format_args as fargs
def main():
a, b = "text", (12, 13)
print "== Unaliased =="
test_text = format_args(a, b)
print test_text # Returns
debug_print(a, b)
print "\n== Aliased =="
test_text = fargs(a, b)
print test_text
debug(a, b)
if __name__ == '__main__':
main()
The output from this is:
== Unaliased ==
code context: test_text = format_args(a, b)
func_name : format_args
('text', (12, 13))
code context: debug_print(a, b)
func_name : debug_print
('text', (12, 13))
== Aliased ==
code context: test_text = fargs(a, b)
func_name : format_args
('text', (12, 13))
code context: debug(a, b)
func_name : debug_print
('text', (12, 13))
As can be seen I've found the correct code context, and I found the name of the calling function, but alas the first reports the alias name and the latter reports the actual name. So my question is whether it is possible to reverse the operation so that I can know that format_args
has been aliased to fargs
, and debug_print
has been aliased to debug
?
Some related issues, which do not address this reversal of aliasing: