Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string object not callable

Tags:

python

string

I am not able to understand why I am getting a Type Error for the following statement

log.debug('vec : %s blasted : %s\n' %(str(vec), str(bitBlasted)))

type(vec)  is unicode
bitBlasted is a list

I am getting the following error

TypeError: 'str' object is not callable
like image 279
nitin Avatar asked Jul 12 '12 20:07

nitin


2 Answers

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.

like image 96
Yatharth Agarwal Avatar answered Sep 23 '22 01:09

Yatharth Agarwal


As mouad said, you've used the name str somewhere higher in the file. That shadows the existing built-in str, and causes the error. For example:

>>> mynum = 123
>>> print str(mynum)
123
>>> str = 'abc'
>>> print str(mynum)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
like image 35
Colin Dunklau Avatar answered Sep 22 '22 01:09

Colin Dunklau