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?.
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__).
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.
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.
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.
You can get this error if you have variable str and trying to call str() function.
Whenever that happens, just issue the following ( it was also posted above)
>>> del str
That should fix it.
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.
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.
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!!')
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.
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
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.
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
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
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.
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
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.
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 also give same error if math library not imported,
import math
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.
Related
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?.
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__).
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.
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.
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.
You can get this error if you have variable str and trying to call str() function.
Whenever that happens, just issue the following ( it was also posted above)
>>> del str
That should fix it.
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.
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.
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!!')
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.
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
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.
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
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
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.
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
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.
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 also give same error if math library not imported,
import math
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.
Given the following integers and calculation
from __future__ import division
a = 23
b = 45
c = 16
round((a/b)*0.9*c)
This results in:
TypeError: 'int' object is not callable.
How can I round the output to an integer?
Somewhere else in your code you have something that looks like this:
round = 42
Then when you write
round((a/b)*0.9*c)
that is interpreted as meaning a function call on the object bound to round, which is an int. And that fails.
The problem is whatever code binds an int to the name round. Find that and remove it.
I got the same error (TypeError: 'int' object is not callable)
def xlim(i,k,s1,s2):
x=i/(2*k)
xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x(1-x))
return xl
... ... ... ...
>>> xlim(1,100,0,0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in xlim
TypeError: 'int' object is not callable
after reading this post I realized that I forgot a multiplication sign * so
def xlim(i,k,s1,s2):
x=i/(2*k)
xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x * (1-x))
return xl
xlim(1.0,100.0,0.0,0.0)
0.005
tanks
Stop stomping on round somewhere else by binding an int to it.
I was also facing this issue but in a little different scenario.
Scenario:
param = 1
def param():
.....
def func():
if param:
var = {passing a dict here}
param(var)
It looks simple and a stupid mistake here, but due to multiple lines of codes in the actual code, it took some time for me to figure out that the variable name I was using was same as my function name because of which I was getting this error.
Changed function name to something else and it worked.
So, basically, according to what I understood, this error means that you are trying to use an integer as a function or in more simple terms, the called function name is also used as an integer somewhere in the code.
So, just try to find out all occurrences of the called function name and look if that is being used as an integer somewhere.
I struggled to find this, so, sharing it here so that someone else may save their time, in case if they get into this issue.
In my case I changed:
return <variable>
with:
return str(<variable>)
try with the following and it must work:
str(round((a/b)*0.9*c))
Sometimes the problem would be forgetting an operator while calculation.
Example:
print(n-(-1+(math.sqrt(1-4(2*(-n))))/2)) rather
it has to be
print(n-(-1+(math.sqrt(1-4*(2*(-n))))/2))
HTH
There are two reasons for this error "TypeError: 'int' object is not callable"
Function Has an Integer Value
Consider
a = [5, 10, 15, 20]
max = 0
max = max(a)
print(max)
This will produce TypeError: 'int' object is not callable.
Just change the variable name "max" to var(say).
a = [5, 10, 15, 20]
var = 0
var = max(a)
print(var)
The above code will run perfectly without any error!!
Missing a Mathematical Operator
Consider
a = 5
b = a(a+1)
print(b)
This will also produce TypeError: 'int' object is not callable.
You might have forgotten to put the operator in between ( '*' in this case )
As mentioned you might have a variable named round (of type int) in your code and removing that should get rid of the error. For Jupyter notebooks however, simply clearing a cell or deleting it might not take the variable out of scope. In such a case, you can restart your notebook to start afresh after deleting the variable.
You can always use the below method to disambiguate the function.
__import__('__builtin__').round((a/b)*0.9*c)
__builtin__ is the module name for all the built in functions like round, min, max etc. Use the appropriate module name for functions from other modules.
I encountered this error because I was calling a function inside my model that used the #property decorator.
#property
def volume_range(self):
return self.max_oz - self.min_oz
When I tried to call this method in my serializer, I hit the error "TypeError: 'int' object is not callable".
def get_oz_range(self, obj):
return obj.volume_range()
In short, the issue was that the #property decorator turns a function into a getter. You can read more about property() in this SO response.
The solution for me was to access volume_range like a variable and not call it as a function:
def get_oz_range(self, obj):
return obj.volume_range # No more parenthesis
This question already has answers here:
Can I use the variable name "type" as function argument in Python?
(5 answers)
Closed 9 years ago.
I've decided to do some coding exercises at coderbyte.com and right in the first exercise (reverse a string) I found this:
def FirstReverse(str):
Even though it works, I don't think it's a good idea to use a built-in type name as a parameter. What do you think?
I know it's kinda silly, but it's my first question at stackoverflow! Thanks =)
In that function definition, str is supposed to be a string, not the built-in function str(). When you do this, you are overwriting the built-in function, so you won't be able to call str() inside the function f, but you can still using it outside. This is because scoping, you are overwriting it in the local scope of f:
def f(str):
print str(123) # will raise an error, because 'str' is not callable (i.e. a function) anymore
f("some string here")
print str(123) # OK
This is a very common mistake, the sooner you learn to avoid it, the sooner you will become a good programmer.
You can use "anything" except keywords as variable/parameter names.
It's usually not a good idea though - as in practically never.
Perhaps the example is from Python1 series where there was a string module, but no str type.
The use of list, dict, str as variable names is a common newby 'mistake'.
I think that it is not a good practice for tutorials, but works OK in practice in this example. I would frown if code was presented to me with that parameters name however.
The more interesting thing to explore is WHY doesn't this tramp on the built-in str function.
Look:
>>> str(123) # the built-in prior to the function 'f' declared
'123'
>>> def f(str): # Note 'str' as parameter
... return str[::-1]
...
>>> f('123') # function works...
'321'
>>> f(str(123)) # function 'f' works with the function 'str' prior
'321'
>>> str(123) # built-in 'str' still works...
'123'
The answer is that in f the str parameter overrides the built-in str function only locally -- inside of f. It is 'restored' to the built-in str after the scope of f is done.
Notice:
>>> def f(str):
... return str('123')[::-1]
...
>>> f(123)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
TypeError: 'int' object is not callable
Since you are calling int inside f you are referring to the parameter, not the function. It gets confusing and, hence, not a great idea to use the name of a built-in as a variable, parameter, etc whether local or global.
I'm not the one that voted Christian's answer down but here's an elaboration if it helps:
Working Function
def f(string):
print ("In function.")
print (string)
print (type(string))
real_string = str(string)
print (type(real_string))
print ("In main.")
int_val = 123
print (type(int_val))
f(int_val)
Results
In main.
In function.
123
class 'int'
class 'str'
Broken Function
def f(str):
print ("In function.")
print (str)
print (type(str))
real_string = str(str)
print (type(real_string))
print ("In main.")
int_val = 123
print (type(int_val))
f(int_val)
Results
----> 5 real_string = str(str)
TypeError: 'int' object is not callable
I am trying to call a function from a string in Python as explained in
Calling a function of a module from a string with the function's name in Python.
Unfortunately, this doesn't work, and the Python interpreter throws an error:
TypeError: 'str' object is not callable
def current(self, t):
if self.iMode == None:
return self.i
else:
return getattr(self, 'iMode')(t)
The error refers to the last line. iMode has been set to sinx(t), that has been declared in the class.
Can anyone help me please?
From the error message it is obvious that your attribute was set to 'sinx(t)' (the string literal).
You should set it the function reference sinx instead, which is a callable.
However, as zhangyangu already said, in you example using getattr() is not needed. Maybe you really want to use a parameter (string reference) instead of the literal 'iMode'?
From the error, your iMode is a string. The iMode is not a method. There must be something wrong with your declaration. And in the class you can use self.iMode, no need to use getattr.
I think you may look for the function like eval.
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?.
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__).
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.
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.
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.
You can get this error if you have variable str and trying to call str() function.
Whenever that happens, just issue the following ( it was also posted above)
>>> del str
That should fix it.
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.
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.
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!!')
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.
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
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.
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
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
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.
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
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.
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 also give same error if math library not imported,
import math
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.