7

It is actually 2 questions. 1) Is there a generic way to get the class name of an instance, so if I have a class

class someClass(object):

I would like a built in way that gives me a string 'someClass'

2) Similar with functions. If I have

def someFunction():
 ....
 print builtinMethodToGetFunctionNameAsString
 return

it would print 'someFunction'

The reason why I am looking for this is, that I have a bit of a jungle of classes and subclasses and for debugging I would like to print where I am, so to all methods I would just want to add something along the lines

print 'Executing %s from %s' %(getFunctionName,getClassName)

So I am looking for a generic command that know the class and the function where it is, so that I can copy and paste the line in all the methods without having to write a separate line for each of them

asked Jun 19, 2013 at 16:26
2
  • How about using a debugger? Commented Jun 19, 2013 at 16:50
  • use .format instead of % 'Executing {} from {}'.format(getFunctionName, getClassName) Commented Jun 19, 2013 at 17:22

2 Answers 2

7

use the __name__ attribute:

Class:

>>> class A:pass
>>> A.__name__
'A'
>>> A().__class__.__name__ #using an instance of that class
'A'

Function:

>>> def func():
... print func.__name__
... 
>>> func.__name__
'func'
>>> func()
func

A quick hack for classes will be:

>>> import sys
>>> class A():
... def func(self):
... func_name = sys._getframe().f_code.co_name
... class_name = self.__class__.__name__
... print 'Executing {} from {}'.format(func_name, class_name)
... 
>>> A().func()
Executing func from A
answered Jun 19, 2013 at 16:28
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Ashwini. For the function, I am looking for a way to print the name without spepcifying the function. Edited my question to explain what my purpose is
3

the function part has already been answered at this SO post. The code would be:

import sys
print sys._getframe().f_code.co_name

For the class part, use: A.__name__ or A().__class__.__name (for an instance)

answered Jun 19, 2013 at 16:51

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.