Posts

Python – Get Object’s Class Name

Q: How do I get a python object’s class name?

 

A: Use the object’s __class__ attribute and then get its __name__ attribute.

 

Another python introspection gem, to get an object’s class name just access its __class__ attribute, for example you can define a method to return the object’s name as follows:

[code]
def get_runtime_type_name(self):
  return self.__class__.__name__
[/code]

Python – Get Name of Current Function

Q: How do I get the name of the current python function, I want to output its name as part of some logging information.

 

A: Just import the ‘inspect’ module and call its stack() method to get access to the call stack, for example, to get the name of the current function:

 

 

The first index indicates the stack position, so to get the name of the parent calling function use:

 

 

or to define a function that returns the name of the function from which it was called:

 

Introspection is one of the really cool features of modern software programming languages!