Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting object name and function name

Tags:

python

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

like image 346
chrise Avatar asked Jun 19 '13 16:06

chrise


People also ask

How do I find the name of an object?

Access the name property on the object's constructor to get the class name of the object, e.g. obj.constructor.name . The constructor property returns a reference to the constructor function that created the instance object. Copied! We accessed the name property on the Object.

What is the function name?

The name property of the Function object is used to get the function's name. name is a read-only property of the Function object.


2 Answers

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
like image 154
Ashwini Chaudhary Avatar answered Oct 28 '22 13:10

Ashwini Chaudhary


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)

like image 25
rickcnagy Avatar answered Oct 28 '22 12:10

rickcnagy