Get fully qualified class name of an object in Python
With the following program
#!/usr/bin/env python
import foo
def fullname(o):
klass = o.__class__
module = klass.__module__
if module == 'builtins':
return klass.__qualname__ # avoid outputs like 'builtins.str'
return module + '.' + klass.__qualname__
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
If you're still stuck on Python 2, you'll have to use __name__
instead of __qualname__
, which is less informative for nested classes - a class Bar
nested in a class Foo
will show up as Bar
instead of Foo.Bar
:
def fullname(o):
klass = o.__class__
module = klass.__module__
if module == '__builtin__':
return klass.__name__ # avoid outputs like '__builtin__.str'
return module + '.' + klass.__name__
Get fully qualified name of a Python class (Python 3.3+)
You are looking for __qualname__
(introduced in Python 3.3):
class A:
class B:
class C:
def me(self):
print(self.__module__)
print(type(self).__name__)
print(type(self).__qualname__)
print(repr(self))
Getting the class name of an instance
Have you tried the __name__
attribute of the class? ie type(x).__name__
will give you the name of the class, which I think is what you want.
>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'
If you're still using Python 2, note that the above method works with new-style classes only (in Python 3+ all classes are "new-style" classes). Your code might use some old-style classes. The following works for both:
x.__class__.__name__
How do you map a fully qualified class name to its class object in Python?
You can use importlib in 2.7:
from importlib import import_module
name = 'xml.etree.ElementTree.ElementTree'
parts = name.rsplit('.', 1)
ElementTree = getattr(import_module(parts[0]), parts[1])
tree = ElementTree()
In older versions you can use the __import__
function. It defaults to returning the top level of a package import (e.g. xml
). However, if you pass it a non-empty fromlist
, it returns the named module instead:
name = 'xml.etree.ElementTree.ElementTree'
parts = name.rsplit('.', 1)
ElementTree = getattr(__import__(parts[0], fromlist=['']), parts[1])
tree = ElementTree()
Simplest way to get fully qualified name of a module
Try something like this:
from bar.baz import spam
print(spam.__name__)
If the name being imported is not a module, you can get the module name and object name like this:
from bar.baz.spam import MyClass
print(MyClass.__module__, MyClass.__name__)
get fully qualified method name from inspect stack
You are always looking at a function context; the method context is already gone by the time the function executes. Technically speaking, functions act as descriptors when accessed as attributes on an instance (instance.method_name
), which return a method object. The method object then, when called, in turn calls the original function with the instance as the first argument. Because this all happens in C code, no trace of the original method object remains on the Python stack.
The stack only needs to keep track of namespaces and the code to be executed for the local namespace. The original function object is no longer needed for these functions, only the attached code object still retains the name of the original function definition for traceback purposes.
If you know the function to be a method, you could search for a self
local name. If present, type(self)
is the class of the instance, which is not necessarily the class the method was defined on.
You would then have to search the class and it's bases (looping over the .__mro__
attribute) to try and locate what class defined that method.
There are a few more snags you need to take into account:
Naming the first argument of a method
self
is only a convention. If someone picked a different name, you won't be able to figure that out without parsing the Python source yourself, or by going up another step in the stack and trying to deduce from that line how the function was called, then retrieve the method and it's.im_self
attribute.You only are given the original name of the function, under which it was defined. That is not necessarily the name under which it was invoked. Functions are first-class objects and can be added to classes under different names.
Although a function was passed in
self
and was defined as part of a class definition, it could have been invoked by manually passing in a value forself
instead of the usual route of the method (being the result of the function acting as a descriptor) passing in theself
reference for the caller.
In Python 3.3 and up, the situation is marginally better; function objects have a new __qualname__
attribute, which would include the class name. The problem is then that you still need to locate the function object from the parent stack frame.
What is a qualified/unqualified name in Python?
It is the path from top-level module down to the object itself.
See PEP 3155, Qualified name for classes and functions.
If you have a nested package named foo.bar.baz
with a class Spam
, the method ham
on that class will have a fully qualified name of foo.bar.baz.Spam.ham
. ham
is the unqualified name.
A qualified name lets you re-import the exact same object, provided it is not an object that is private to a local (function) namespace.
Related Topics
Splitting a Pandas Dataframe Column by Delimiter
Python's Insert Returning None
Google Colab: How to Read Data from My Google Drive
Get Lat/Long Given Current Point, Distance and Bearing
Python: Count Repeated Elements in the List
Pandas Split Column into Multiple Columns by Comma
Reimport a Module While Interactive
Python: Converting from Iso-8859-1/Latin1 to Utf-8
Timeit Versus Timing Decorator
Flask to Return Image Stored in Database
How to Escape Strings for SQLite Table/Column Names in Python
Find Column Name in Pandas That Matches an Array
What's the Difference Between %S and %D in Python String Formatting
Pip Installing in Global Site-Packages Instead of Virtualenv
Django Upgrading to 1.9 Error "Appregistrynotready: Apps Aren't Loaded Yet."