[Tutor] 'module' object has no attribute (setting a class attribute)

Dave Angel davea at ieee.org
Sat Oct 16 13:43:15 CEST 2010

On 2:59 PM, Tim Johnson wrote:
> My intention is to set a class attribute so that any number of
> instantiations will have this value.
> the module is tmpl.py. the class is tmpl.
> if from the script I do this:
> import tmpl
> tmpl.tmpl.templatepath = kbLib.templatepath
> I get error message:
> 'module' object has no attribute 'templatepath'
> I ended up getting completely befuddled, and then realized that the
> problem was the right side of the assignment statement. I.E.  I had
> a typo on the right and python was not informing me of *which*
> module didn't have the attribute
> I have two questions regarding this:
> 1)Am I using the correct method to set a class attribute?
> 2)Is there a system configuration that would cause the
> AttributeError exception to print out the module name.
> (In this cause it was 'kbLib' not 'tmpl'.
> thanks
1) The code is correct.  But it'd be much clearer if you followed 
conventions and named your class with a leading uppercase.  So the 
module would be called tmpl, and the class would be called Tmpl.

2) For the general case, this error is about fetching attributes from 
arbitrary objects.  Such an object is not always bound to a single name, 
so it reports the object's type, rather than its name.  In this 
particular case, a module has a unique name, so the message could have 
been more helpful.  But it's not clear how the error display logic could 
have readily known that.

Two things could help you figure it for yourself more quickly.  a) On 
the left side of such an assignment, this error can only refer to 
attributes other than the last, since the last one is being created 
here, and it wouldn't matter if it already existed.  b) You could 
refactor the line, and see where the error message moves to.  Let's try 

a = kbLib.templatepath
tmpl.Ttmpl.templatepath = a

If the line that now gets the error had still been confusing, you could 
try to refactor that in turn.


More information about the Tutor mailing list