class method to create object of a given class

def _from_class(cls, class_name, module_name=None, *args, **kwargs):
        """ class method to create object of a given class """
        def _get_module(module_name):
            names = module_name.split(".")
            module = __import__(names[0])
            for i in xrange(1, len(names)):
                module = getattr(module, names[i])
            return module

        if module_name:
            # module = globals()[module_name]
            # module = __import__(module_name)
            module = _get_module(module_name)
            class_ = getattr(module, class_name)
        else:
            class_ = globals()[class_name]

        if not issubclass(class_, PersistentObject):
            t = class_.__name__, PersistentObject.__name__
            raise TypeError, 'Requested object type %s must be subtype of %s ' % t

        # workaround to mimic FactoryType to work well with FactoryObject.
        name = str(args[0]) if args else cls.__name__
        name = kwargs['name'] if 'name' in kwargs else name
        if hasattr(cls, 'get'):
            instance = cls.get(name)
            if instance:
                return instance

        instance = class_.__new__(class_, *args, **kwargs)
        instance.__init__(*args, **kwargs)
        return instance