[Oh god please stop/avoid using Google Groups with its godawful
reply-quoting style that adds excessive blank lines]
Because I have this situation:
I have used a dictionary with "function_name":value pair in the top of
the code. Now when some function is called, I need to print the value
assigned to its name in the dictionary (the functions are defined after the
dictionary). Now there is only one bad way-around for me: I need to
hard-code the name in the function like this:
def function_name():
print(dict_name.get("function_name"))
but ofcourse it is a bad thing to do because I have a lot of this type of
functions. It would be better if I can can use the same code for all of
them, because they are all essentially doing the same thing.
I agree with the general outline of Mitya's suggestion, i.e. refactor the
"print the associated value" step into a separate function, thus obviating
the self-reference issue; it'd be bad to repeat that code in each function
anyway.
Anyhow, here's a simple variation that exploits decorators (because they're
generally awesome & one of my favorite features):
def printing_name_beforehand(func):
def wrapper(*args, **kwargs):
print(the_dict.get(func.__name__))
return func(*args, **kwargs)
return wrapper
Usage:
@printing_name_beforehand
def some_func(...):
# whatever
(Forgive me if there are typos; composing this reply on a tablet is
cumbersome.)