Hanno S. Hanno S. - 5 months ago 54
Python Question

Get fully qualified class name of an object in Python

For logging purposes I want to retrieve the fully qualified class name of a Python object. (With fully qualified I mean the class name including the package and module name.)

I know about

x.__class__.__name__
, but is there a simple method to get the package and module?

Answer

With the following program

#! /usr/bin/env python

import foo

def fullname(o):
  return o.__module__ + "." + o.__class__.__name__

bar = foo.Bar()
print fullname(bar)

and Bar defined as

class Bar(object):
  def __init__(self, v=42):
    self.val = v

the output is

$ ./prog.py
foo.Bar
Comments