November 26th, 2003, 12:45 PM
Accessing function/class name from within the function/class
I have this code :
a = sky()
I would like the function sun to return sky.sun and preferably with any function arguments too. The function's name is stored in the __name__ attribute, but how do I get access to a functions __name__ attribute from within the function?
I have tried func.__name__ etc but that won't compile.
November 26th, 2003, 03:08 PM
This was actually shockingly simple, more so than i imagined.. the class method doesn't even have to return anything if you don't wish!
>>> class sky(object):
>>> print '%s.%s' % (sky.__name__, sky.sun.__name__)
>>> #you can also do it like this, although i'd use the first..
>>> print sky.__name__ + '.' + sky.sun.__name__
Ok so you see how to get and format the results.. heres you class where sun returns the data you wanted..
>>> class sky(object):
return '%s.%s' % (sky.__name__, sky.sun.__name__)
One question though, why are you doing this? particually why are you inheriting from 'object'.. Oh, just for your info you don't compile Python code
November 26th, 2003, 03:42 PM
Yet another simple solution - though in opposite direction
return '%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name)
Unlike netytan's solution, it is the true reflection (no hard-coded names of function and class)
November 26th, 2003, 05:40 PM
It's for testing/debugging. I want a piece of code I can paste into any function so I can see where (un)expected things happen.
At the moment, I need it for a cgi-script (MVC architecture), so errors/exceptions/messages can be sent from a database connector class (model) via a Controller class to a View class where it is displayed.
I'm just trying to be forward-compatible with the "new-style" classes, and this was just a made up class anyway.
I know Python is an interpreted language, but in a way it is still compiled
It's more work to hardcode the function names, and I might type the wrong function name, so I must avoid that.
I found some useful functions in the inspect module and arrived at this solution. Just like what Igor suggested with the addition of the function arguments.
It does the job now, but I will try to make it shorter and exclude the self argument to the function.
a,b,c,d = inspect.getargvalues(inspect.currentframe())
debug = '%s.%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name, inspect.formatargvalues(a,b,c,d))