import class from string

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jul 4 18:51:02 EDT 2012


On Wed, 04 Jul 2012 13:27:29 -0700, Mariano DAngelo wrote:

> Hi I'm trying to create a class from a string.... This is my code, but
> is not working....
> 
> 'myshop.models.base'
> module_name, class_name = model.rsplit(".", 1) 
> module = importlib.import_module(module_name) 
> class_ = getattr(module, class_name)()
> 
> 
> Anyone know what I'm doing wrong....

What version of Python are you using?

What result do you expect?

What result do you actually get?

When asking for help, please take the time to create a short, self-
contained, correct example that anyone can actually run:

http://sscce.org/

In the above, you have a bare string that does nothing; a name "model" 
that is undefined; and what looks like a module that isn't imported 
(importlib). We have no idea of what problem *you* see, because we can't 
run your code and you don't show us the error.

But the general idea is correct, at least in Python 3.2:

import importlib
model = 'unittest.suite.BaseTestSuite'
module_name, class_name = model.rsplit(".", 1)
module = importlib.import_module(module_name)
class_ = getattr(module, class_name)

At the end of which, class_ is the expected BaseTestSuite class.


I suspect that your error is that after you get the class object using 
getattr, you then *call* the class object but give no arguments, and the 
class requires arguments.

You say:
    class_ = getattr(module, class_name)()  # note the extra () brackets

I say:
    class_ = getattr(module, class_name)


Either that or you have a bug in your module and it can't be imported. Or 
you have misspelled the module name, or the class. Or forgotten to import 
importlib. Or are shadowing it with your own module. Who knows? Without 
seeing the error, I'm just guessing.



-- 
Steven



More information about the Python-list mailing list