[Tutor] getattr works sometimes

Steven D'Aprano steve at pearwood.info
Wed Oct 3 02:19:24 CEST 2012

On 03/10/12 03:44, Tino Dai wrote:
> Hi All,
>        I'm using the get_class from:
> http://stackoverflow.com/questions/452969/does-python-have-an-equivalent-to-java-class-forname

Do you mean this function?

def get_class( kls ):
     parts = kls.split('.')
     module = ".".join(parts[:-1])
     m = __import__( module )
     for comp in parts[1:]:
         m = getattr(m, comp)
     return m

At only seven lines, it is perfectly acceptable to copy it into your
email for the benefit of those who are blocked from accessing the web
but still have access to email. Of course it is good to give credit
to the original source as well.

The name is misleading, because it does not just get classes, it
gets any object you like:

py> get_class("math.pi")

> and the get_class class works sometime for finding modules within a
> certain directory.

The get_class function will find modules anywhere that they would be
found by the import statement, that is, in the Python module import
search path (sys.path).

> If the get_class doesn't work, it throws an AttributeError.

If the module does not exist, or cannot be found, get_class will raise
ImportError. If the module is successfully found, but the dotted name
does not exist, get_class will raise AttributeError.

> The module exists in the directory, and I'm trying to debug this. Does
> anybody have any hints to go about debug this?

The usual advise: read the error message, it tells you what went wrong:

py> get_class("datetime.datime")
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<stdin>", line 6, in get_class
AttributeError: 'module' object has no attribute 'datime'

I typed the name wrong. It's "datetime", not "datime".

py> get_class("datetime.datetime")
<class 'datetime.datetime'>


More information about the Tutor mailing list