Search code examples
pythonintrospection

How do you map a fully qualified class name to its class object in Python?


You can get the fully qualified class name of a Python object like this (see this question):

>>> import Queue
>>> q = Queue.PriorityQueue()
>>> def fullname(o):
    return o.__module__ + "." + o.__class__.__name__  
...   
>>> fullname(q)
'Queue.PriorityQueue'
>>> 

How do you do the inverse, ie, map a fully qualified class name like 'Queue.PriorityQueue' to its associated class object (Queue.PriorityQueue)?


Solution

  • 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()