Shadowing the built-in
Either as Collin said, you could be shadowing the built-in str
:
>>> str = some_variable_or_string #this is wrong
>>> str(123.0) #Or this will happen
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
One solution would be to change the variable name to str_
or something. A better solution would be to avoid this kind of Hungarian naming system -- this isn't Java, use Python's polymorphism to its fullest and use a more descriptive name instead.
Not defining a proper method
Another possibility is that the object may not have a proper __str__
method or even one at all.
The way Python checks for the str
method is:-
- the
__str__
method of the class
- the
__str__
method of its parent class
- the
__repr__
method of the class
- the
__repr__
method of its parent class
- and the final fallback: a string in form of
<module>.<classname> instance at <address>
where <module>
is self.__class__.__module__
, <classname>
is self.__class__.__name__
and <address>
is id(self)
Even better than __str__
would be to use the new __unicode__
method (in Python 3.x, they're __bytes__
and __str__
. You could then implement __str__
as a stub method:
class foo:
...
def __str__(self):
return unicode(self).encode('utf-8')
See this question for more details.