Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 827
Jim Ferrans Avatar asked Feb 02 '23 14:02

Jim Ferrans


2 Answers

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()
like image 168
Eryk Sun Avatar answered Feb 05 '23 05:02

Eryk Sun


For Python 2.6/2.7



    import sys
    def hasModule(moduleName):
        return moduleName in sys.modules

    def getModule(moduleName):
        if hasModule(moduleName):
            return sys.modules[moduleName]

    def loadModule(moduleName):
        if not hasModule(moduleName):
            return __import__(moduleName)
        return getModule(moduleName)

    def createInstance(fqcn, *args):
        paths = fqcn.split('.')
        moduleName = '.'.join(paths[:-1])
        className = paths[-1]
        module = loadModule(moduleName)
        if module is not None:
            return getattr(module, className)(*args)

    pq = "Queue.PriorityQueue"
    pqObj = createInstance(pq)
    pqObj.put(1)
    print pqObj.get() #1

like image 25
t w Avatar answered Feb 05 '23 05:02

t w