TypeError: 'str' object is not callable (Python)

Python

Python Problem Overview


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

Python Solutions


Solution 1 - Python

This is the problem:

global str

str = str(mar)

You are redefining what str() means. str is the built-in Python name of the string type, and you don't want to change it.

Use a different name for the local variable, and remove the global statement.

Solution 2 - Python

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.

Solution 3 - Python

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.

Solution 4 - Python

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.

Solution 5 - Python

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

Solution 6 - Python

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

>>> del str

That should fix it.

Solution 7 - Python

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.

Solution 8 - Python

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.

Solution 9 - Python

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!!')

Solution 10 - Python

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.

Solution 11 - Python

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"

Solution 12 - Python

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

Solution 13 - Python

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!

Solution 14 - Python

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

Solution 15 - Python

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.

Solution 16 - Python

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.

Solution 17 - Python

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

Solution 18 - Python

In case if you never used str keyword or str() method in your code you might be wondering by looking at the existing answers to this question. So, let me write down your solution,

Go to your code and check are there a variable name which exactly similar to your method name. For example in this scenario,

class Shapes:
    def __init__(self,colour):
        self.colour=colour
    def colour(self):
        print("colour:",self.colour)

in-class Shape I have a variable named color and I also have a method named color. So what actually happens is when you creating an object and calling your method through that object python interpreter thinks you are referring to the variable, not the method.

myShape=Circle("pink",7)
myShape.colour()

So the simple solution is to change either the method name or the variable name.

Solution 19 - Python

I also got this error. For me it was just a typo:

I wrote:

driver.find_element_by_id("swal2-content").text()

while it should have been:

driver.find_element_by_id("swal2-content").text

Solution 20 - Python

It also give same error if math library not imported,

import math

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionP&#39;saoView Question on Stackoverflow
Solution 1 - PythonGreg HewgillView Answer on Stackoverflow
Solution 2 - Pythonn611x007View Answer on Stackoverflow
Solution 3 - PythonThorSummonerView Answer on Stackoverflow
Solution 4 - PythonAlexander H. StebnerView Answer on Stackoverflow
Solution 5 - PythonDmitryView Answer on Stackoverflow
Solution 6 - PythonchikitinView Answer on Stackoverflow
Solution 7 - PythonLucianoView Answer on Stackoverflow
Solution 8 - PythonGabriel FairView Answer on Stackoverflow
Solution 9 - Pythonkarthik akinapelliView Answer on Stackoverflow
Solution 10 - PythonLuisView Answer on Stackoverflow
Solution 11 - PythonAnis JonischkeitView Answer on Stackoverflow
Solution 12 - PythonAhmadiahView Answer on Stackoverflow
Solution 13 - PythonJoseph GillView Answer on Stackoverflow
Solution 14 - PythonNadavoView Answer on Stackoverflow
Solution 15 - Pythonblueinc spatialView Answer on Stackoverflow
Solution 16 - PythonBob SteinView Answer on Stackoverflow
Solution 17 - PythonjHopsView Answer on Stackoverflow
Solution 18 - PythonINDRAJITH EKANAYAKEView Answer on Stackoverflow
Solution 19 - PythonEyal SoolimanView Answer on Stackoverflow
Solution 20 - PythonKiranView Answer on Stackoverflow