103

I have some code like:

def example(parameter):
    global str
    str = str(parameter)
    print(str)

example(1)
example(2)

The first call to example works, but then the second time around I get an error like:

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    example(2)
  File "test.py", line 3, in example
    str = str(parameter)
TypeError: 'str' object is not callable

Why does this happen, and how can I fix it?


If you are in an interactive session and encountered a problem like this, and you want to fix the problem without restarting the interpreter, see How to restore a builtin that I overwrote by accident?.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
P'sao
  • 2,946
  • 11
  • 39
  • 48
  • I [edit]ed the question significantly to produce a proper [mre] - originally there was a *lot* of code irrelevant to the question (which was not considered in any answers - and any other issues there would make the question lack the proper focus). I also removed a follow-up reply related to the exact original code and precisely how to fix it in context - because this is **not a discussion forum**. – Karl Knechtel Jul 24 '22 at 19:54
  • This question has become a useful canonical, so I want it to look as good as possible. While it was originally asked 11 years ago, I would like to offer a gentle reminder to everyone to try to [track down](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and [understand](https://meta.stackoverflow.com/questions/261592) problems before posting. – Karl Knechtel Jul 24 '22 at 19:55

20 Answers20

161

Where the code says:

global str
str = str(parameter)

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.

Note that if you used code like this at the Python REPL, then the assignment to the global str will persist until you do something about it. You can restart the interpreter, or del str. The latter works because str is not actually a defined global variable by default - instead, it's normally found in a fallback (the builtins standard library module, which is specially imported at startup and given the global name __builtins__).

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 7
    not meant to be used, but alternatively, the `str()` function is also available as `__builtins__.str()`. Of course it is a bad idea to use that in 99.9999% of the cases, I guess. – n611x007 Sep 26 '13 at 20:23
  • In the original code, the `global` statement was necessitated to avoid [a different problem](https://stackoverflow.com/questions/370357). After the renaming, it is useless, but not directly harmful. – Karl Knechtel Jul 24 '22 at 19:58
121

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.

n611x007
  • 8,952
  • 8
  • 59
  • 102
  • Having a property and a method with the same name, overwriting the method with a string, and then trying to execute that method/string also gave TypeError: 'str' object is not callable – Puggan Se Jun 28 '20 at 23:38
26

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.

ThorSummoner
  • 16,657
  • 15
  • 135
  • 147
  • 1
    it might be nice to have shadowing logged and something like a strict mode cause a RuntimeWarning of some kind when this happens, but eh; it is totally valid python to replace an attribute with a method and vice versa by the spec – ThorSummoner Jul 23 '20 at 00:04
26

Note that TypeError: 'str' object is not callable means only that there is an attempt to call (i.e., use function-call syntax) a string (i.e., any name that previously had a string assigned to it). Using any other built-in method as variable name can cause the exact same error message.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
19

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

Dmitry
  • 14,306
  • 23
  • 105
  • 189
13

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

>>> del str

That should fix it.

chikitin
  • 762
  • 6
  • 28
8

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.

Luciano
  • 1,119
  • 12
  • 18
6

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.

Gabriel Fair
  • 4,081
  • 5
  • 33
  • 54
5

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.

MarianD
  • 13,096
  • 12
  • 42
  • 54
Luis
  • 61
  • 1
  • 4
5
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!!')
MarianD
  • 13,096
  • 12
  • 42
  • 54
karthik akinapelli
  • 710
  • 1
  • 7
  • 14
3

This problem can be caused by code like:

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

You can concatenate string literals by putting them next to each other, like "Foo" "Bar". However, because of the open parenthesis, the code was interpreted as an attempt to call the string "Foo" as if it were a function.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Anis Jonischkeit
  • 914
  • 7
  • 15
  • Note that this kind of concatenation can **only** be done with string **literals**. It cannot be done with anything that has to do any kind of computation at runtime. The concatenation happens *while compiling the code*. – Karl Knechtel Aug 09 '22 at 06:21
3

This error can also occur as a result of trying to call a property (as though it were a function):

class Example:
    @property
    def value():
        return 'test'

e = Example()
print(e.value()) # should just be `e.value` to get the string
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Joseph Gill
  • 1,067
  • 11
  • 18
  • And more sneakily also true if you are using the setter method for that property and calling that with parentheses. – Lokal_Profil Aug 05 '19 at 17:02
1

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
Ahmadiah
  • 476
  • 5
  • 12
  • Two problems with this example: 1) `a(3) = 1` would be a syntax error ("can't assign to function call"), so code like that wouldn't get to the runtime error in the first place; 2) strings are immutable, so even with `[]`, it would cause a different error again to try to assign like that. – Karl Knechtel Jul 24 '22 at 20:08
1

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

Nadavo
  • 250
  • 2
  • 9
1

This error could also occur with code like:

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

myShape = Shape("pink")
myShape.colour()

In the __init__ method, we assign an attribute colour, which has the same name as the method colour. When we later attempt to call the method, the instance's attribute is looked up instead. myShape.colour is the string "pink", which is not callable.

To fix this, change either the method name or the variable name.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
INDRAJITH EKANAYAKE
  • 3,894
  • 11
  • 41
  • 63
0

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
Eyal Sooliman
  • 1,876
  • 23
  • 29
-1

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.

-1

I realize this is not a runtime warning, but PyCharm gave me this similarly-worded IDE warning:

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

This was because the IDE 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):
    return w.to_json()

Then the warning went away. This same check may also prevent the runtime exception in the original question.

Bob Stein
  • 16,271
  • 10
  • 88
  • 101
  • This question is not about IDE warnings. – Karl Knechtel Jul 24 '22 at 20:14
  • @KarlKnechtel you are right, I blew past that, thank you. Reworded to make that distinction. However, wouldn't you agree that checking `callable()` could also prevent the runtime exception? The original question is obviously a dumb mistake (redefining `str`) but I suggest that it is good when answers go beyond the original question to resolve other situations with the same exception message. The [#2](https://stackoverflow.com/a/14936426/673991) and [#3](https://stackoverflow.com/a/31488569/673991) answers here do that. – Bob Stein Jul 27 '22 at 13:18
  • Checking whether something is `callable` before calling it would prevent an exception, but it wouldn't address the underlying logical error. Answers are supposed to address the question, not the error message generally. There's an underlying tension there: the questions the site needs to be most useful are not necessarily the ones that people would ask out of self interest. – Karl Knechtel Jul 27 '22 at 18:57
  • More to the point, this question is used as a canonical for questions where OP has made a similar redefinition of a built-in (redefining `input` is also common), so answers for other cases are a bit distracting. – Karl Knechtel Jul 27 '22 at 18:58
  • @KarlKnechtel it's a good point you make that Stack Overflow harnesses questioner self interest to generate content, which is then expected to serve needs far wider than those of the original questioner. Until the universe resolves that discordance better, I suggest a more relaxed standard for how tightly an answer fits a question. This site is more useful if same-symptom issues get some mention. Would a comment be better? Error message text search is one of the best vectors we have of getting help. Of course this discussion belongs in chat. I expect we should be talking past each other there. – Bob Stein Jul 28 '22 at 14:09
  • @KarlKnechtel walking back a bit, I concede it would be better if a google search on [this exception text](https://www.google.com/search?q=typeerror+%27str%27+object+is+not+callable+site%3Astackoverflow.com) (or similarly worded IDE warning) led to a different question with different answers. Another discordance of Stack Overflow is how deeply it relies on google for matching users with content. I'm nonetheless inclined to drop breadcrumbs in this difficult-to-forage forest. – Bob Stein Jul 28 '22 at 14:24
-1

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
jHops
  • 340
  • 1
  • 3
  • 11
-1

It also give same error if math library not imported,

import math
Kiran
  • 1,176
  • 2
  • 14
  • 27