[python] TypeError: 'str' object is not callable (Python)

Code:

import urllib2 as u
import os as o
inn = 'dword.txt'
w = open(inn)
z = w.readline()
b = w.readline()
c = w.readline()
x = w.readline()
m = w.readline()
def Dict(Let, Mod):
    global str
    inn = 'dword.txt'
    den = 'definitions.txt'

    print 'reading definitions...'

    dell =open(den, 'w')

    print 'getting source code...'
    f = u.urlopen('http://dictionary.reference.com/browse/' + Let)
    a = f.read(800)

    print 'writing source code to file...'
    f = open("dic1.txt", "w")
    f.write(a)
    f.close()

    j = open('defs.txt', 'w')

    print 'finding definition is source code'
    for line in open("dic1.txt"):
        if '<meta name="description" content=' in line:
           j.write(line)

    j.close()

    te = open('defs.txt', 'r').read().split()
    sto = open('remove.txt', 'r').read().split()

    print 'skimming down the definition...'
    mar = []
    for t in te:
        if t.lower() in sto:
            mar.append('')
        else: 
            mar.append(t)
    print mar
    str = str(mar)
    str = ''.join([ c for c in str if c not in (",", "'", '[', ']', '')])

    defin = open(den, Mod)
    defin.write(str)
    defin.write('                 ')
    defin.close()

    print 'cleaning up...'
    o.system('del dic1.txt')
    o.system('del defs.txt')
Dict(z, 'w')
Dict(b, 'a')
Dict(c, 'a')
Dict(x, 'a')
Dict(m, 'a')
print 'all of the definitions are in definitions.txt'

The first Dict(z, 'w') works and then the second time around it comes up with an error:

Traceback (most recent call last):
  File "C:\Users\test.py", line 64, in <module>
    Dict(b, 'a')
  File "C:\Users\test.py", line 52, in Dict
    str = str(mar)
TypeError: 'str' object is not callable

Does anyone know why this is?

@Greg Hewgill:

I've already tried that and I get the error:

Traceback (most recent call last):
 File "C:\Users\test.py", line 63, in <module>
    Dict(z, 'w')
  File "C:\Users\test.py", line 53, in Dict
   strr = ''.join([ c for c in str if c not in (",", "'", '[', ']', '')])
TypeError: 'type' object is not iterable

This question is related to python

The answer is


it is recommended not to use str int list etc.. as variable names, even though python will allow it. this is because it might create such accidents when trying to access reserved keywords that are named the same


I had the same error. In my case wasn't because of a variable named str. But because I named a function with a str parameter and the variable the same.

same_name = same_name(var_name: str)

I run it in a loop. The first time it run ok. The second time I got this error. Renaming the variable to a name different from the function name fixed this. So I think it's because Python once associate a function name in a scope, the second time tries to associate the left part (same_name =) as a call to the function and detects that the str parameter is not present, so it's missing, then it throws that error.


I had yet another issue with the same error!

Turns out I had created a property on a model, but was stupidly calling that property with parentheses.

Hope this helps someone!


I got this warning from an incomplete method check:

if hasattr(w, 'to_json'):
    return w.to_json()
             ######### warning, 'str' object is not callable

It assumed w.to_json was a string. The solution was to add a callable() check:

if hasattr(w, 'to_json') and callable(w.to_json):

Then the warning went away.


In my case, I had a Class with a method in it. The method did not have 'self' as the first parameter and the error was being thrown when I made a call to the method. Once I added 'self,' to the method's parameter list, it was fine.


In my case I had a class that had a method and a string property of the same name, I was trying to call the method but was getting the string property.


An issue I just had was accidentally calling a string

"Foo" ("Bar" if bar else "Baz")

You can concatenate string by just putting them next to each other like so

"Foo" "Bar"

however because of the open brace in the first example it thought I was trying to call "Foo"


str = 'Hello World String'    
print(str(10)+' Good day!!')

Even I faced this issue with the above code as we are shadowing str() function.

Solution is:

string1 = 'Hello World String'
print(str(10)+' Good day!!')

You can get this error if you have variable str and trying to call str() function.


Another case of this: Messing with the __repr__ function of an object where a format() call fails non-transparently.

In our case, we used a @property decorator on the __repr__ and passed that object to a format(). The @property decorator causes the __repr__ object to be turned into a string, which then results in the str object is not callable error.


While not in your code, another hard-to-spot error is when the % character is missing in an attempt of string formatting:

"foo %s bar %s coffee"("blah","asdf")

but it should be:

"foo %s bar %s coffee"%("blah","asdf")

The missing % would result in the same TypeError: 'str' object is not callable.


It is important to note (in case you came here by Google) that "TypeError: 'str' object is not callable" means only that a variable that was declared as String-type earlier is attempted to be used as a function (e.g. by adding parantheses in the end.)

You can get the exact same error message also, if you use any other built-in method as variable name.


FWIW I just hit this on a slightly different use case. I scoured and scoured my code looking for where I might've used a 'str' variable, but could not find it. I started to suspect that maybe one of the modules I imported was the culprit... but alas, it was a missing '%' character in a formatted print statement.

Here's an example:

x=5
y=6
print("x as a string is: %s.  y as a string is: %s" (str(x) , str(y)) )

This will result in the output:

   TypeError: 'str' object is not callable

The correction is:

x=5
y=6
print("x as a string is: %s.  y as a string is: %s" % (str(x) , str(y)) )

Resulting in our expected output:

x as a string is: 5. y as a string is: 6

it could be also you are trying to index in the wrong way:

a = 'apple'
a(3) ===> 'str' object is not callable

a[3] = l

Check your input parameters, and make sure you don't have one named type. If so then you will have a clash and get this error.


Whenever that happens, just issue the following ( it was also posted above)

>>> del str

That should fix it.