How To Fix Python Error TypeError: ‘str’ Object Is Not Callable

This article summarizes several cases that will throw Python TypeError: ‘str’ object is not callable or TypeError: ‘module’ object is not callable, it will also tell you how to fix the error in each case.

1. Case1: Define str As A Python Variable.

1.1 How To ReProduce Python Error TypeError: ‘str’ Object Is Not Callable.

  1. When I develop a python program, I want to use the Python built-in function str() to convert a number variable to a string type. But I meet the below error Typeerror: ‘str’ Object Is Not Callable. 
    >>> x = 1.99
    >>>
    >>> str(x)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'str' object is not callable
  2. This error confused me a lot for some time. But I finally fix it after googling it. The reason for this error is that I use the global variable name str in the same python interpreter, and I had assigned a string value to that variable str.
  3. So the python interpreter treats str as a variable name other than the built-in function name str(). So it throws out TypeError: ‘str’ object is not callable. Below is the full python source code.
    >>> global str
    >>>
    # some times ago, I assign string 'hello' to str variable, so python interpreter think str is a string variable.
    >>> str = 'hello'
    >>>
    ......
    ......
    ......
    >>> x= 1.99
    # so when I invoke str() function, the interpreter think str is a string variable then below error is thrown.
    >>> str(x)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'str' object is not callable

1.2 How To Fix Python Error TypeError: ‘str’ Object Is Not Callable.

  1. It is very easy to fix this error.
  2. Run del str command to delete the variable.
  3. After that, you can call the function str() without error.
    >>> global str
    >>> 
    >>> str = 'hello'
    >>> 
    >>> x = 1.99
    >>> 
    >>> str(x)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'str' object is not callable
    >>> 
    >>> del str
    >>> 
    >>> str(x)
    '1.99'

1.3 Conclusion.

  1. Do not declare the python variable name as the same as the python built-in function name or keyword.

2. Case2: Use A Python String As A Function Name.

2.1 Reproduce.

  1. In this case, it uses the python easygui module to get an integer number from user input, and then calculate the number as a percentage number. Please see below source code.
    # Import all functions from easygui module.
    from easygui import *
    
    
    def easygui_str_type_error():
        
        # Prompt a GUI dialog to gather user input integer number.
        number_str = enterbox("Please input an integer number as percentage.")
        
        # Convert the string number to integer value.
        number_int = int(number_str)
        
        if number_int > 100:
            
            msgbox("The input number is bigger than 100, it is invalid.")
        
        else:
            # Display a GUI dialog to show the percentage.
            msgbox("The percentage is "(number_int * 0.01))
            
    
    
    if __name__ == '__main__':
        
        easygui_str_type_error()
  2. When you run the above python code, it will throw the below error message.
    Traceback (most recent call last):
      File "/string/PythonStrTypeError.py", line 31, in <module>
        easygui_str_type_error()
      File "/string/PythonStrTypeError.py", line 23, in easygui_str_type_error
        msgbox("The percentage is "(number_int * 0.01))
    TypeError: 'str' object is not callable
    

2.2 How To Fix.

  1. The error occurs at the code line msgbox("The percentage is "(number_int * 0.01)).
  2. This is because there is nothing between the string literal (“The percentage is “) and the (number_int * 0.01) parenthesis.
  3. So Python interpreter treats the string “The percentage is ” as an invokable object ( a function name ), but the code’s real purpose is to splice two strings.
  4. So we can change the code to msgbox("The percentage is " + str(number_int * 0.01)) to fix the error.
  5. We can also use string formatting in a more regular way.
    msgbox("The percentage is {} ".format(number_int * 0.01))

3. Case3: Call The Module Name Like A Function.

3.1 Reproduce The TypeError: ‘module’ object is not callable.

  1. When I use the python builtwith module to detect the technology used by the target website, it throws the error message TypeError: ‘module’ object is not callable.
  2. The reason for this error is that you call the module object like a function.
  3. In my example, after I install the builtwith module, I run the python code like below, and the code throws the error.
    # Import the builtwith module
    >>> import builtwith
    
    # Call the builtwith module like a function as below, and this line of code will throw the TypeError.
    >>> builtwith('http://www.dev2qa.com')
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: 'module' object is not callable

3.2 How To Fix The Python TypeError: ‘module’ object is not callable.

  1. To fix this error, you should call a function in the module such as builtwith.parse(‘http://www.dev2qa.com’) like below.
    >>> builtwith.parse('http://www.dev2qa.com')
    {'cdn': ['CloudFlare'], 'analytics': ['Clicky'], 'advertising-networks': ['Google AdSense'], 'javascript-frameworks': ['Prototype', 'React', 'RequireJS', 'jQuery'], 'web-frameworks': ['Twitter Bootstrap'], 'ecommerce': ['WooCommerce'], 'cms': ['WordPress'], 'programming-languages': ['PHP'], 'blogs': ['PHP', 'WordPress']}
    
  2. Then you can find the error is fixed.
  3. So you should remember that you can not call the module name like a function, you should call a function in the module, then the error will be fixed.
  4. There are also other cases that throw this error, such as the python socket module has a socket class.
  5. If you want to create a python socket object, you need to call the code socket.socket(……), if you call the socket class directly, it will throw the TypeError: ‘module’ object is not callable also.
  6. From the below source code, we can see the difference between the python socket module and socket class.
    >>> import socket # import the python socket module.
    >>> socket # print out the socket module description text, we can see that it is a module.
    <module 'socket' from 'C:\Python37\lib\socket.pyc'>
    >>> socket.socket # call the socket class in the socket module, you can see it is a socket class.
    <class 'socket._socketobject'>
  7. If you import the socket class from the socket module first ( from socket import socket ), then you can call the socket class constructor to create the socket object directly without error.
    >>> from socket import socket # import the socket class from the socket module.
    >>> socket # then the call to the socket will reference to the socket class, you can call socket(...) directly to create the socket object.
    <class 'socket.socket'>

7 thoughts on “How To Fix Python Error TypeError: ‘str’ Object Is Not Callable”

  1. Radiotelescope = instrument(name=’Uirapuru’, 
               lon=lon, 
               lat=lat, 
               elev=elev, 
               timezone=fuso, 
               verbose=True, 
               Alt=Alt, 
               Az=Az,
               fwhm = fwhm).set_observatory()
    Uirapuru.set_observatory().name
    Uirapuru.backend = backend

  2. a=int(input(‘Enter your obtain marks: ‘))
    b=int(input(‘Enter your total marks: ‘))
    marks=(a+b)
    print(marks)

    TypeError                                 Traceback (most recent call last)
    <ipython-input-104-97ec1f24e33d> in <module>
          2 b=int(input('Enter your total marks: '))
          3 marks=(a+b)
    ----> 4 print(marks)
    
    TypeError: 'str' object is not callable
    
  3. Hello, I do not even have any str variables and it still gives me Type error.

    My code:

    characters = [‘a”b”c”d”e”f”g”h”i”j”k”l”m”n”o”p”q”r”t”u”v”w”x”y”z’]
    numbers = [‘1”2”3”4”5”6”7”8”9”10”11”12”13”14”15”16”17”18”19”20”21”22”23”24’]
    input = input(‘Write Text: ‘)
    input = input.lower()
    output = []
    for character in input:
    number = ord(character) – 96
    output.append(number)

    print(output)

    MAX = 100

    # Function to print Matrix
    def printMatrix(M, rowSize, colSize):

    global row1
    for i in range(rowSize):

    for j in range(colSize):

    print(M[i][j], end = ” “)

    print()
    # Function to multiply two matrices

    # A[][] and B[][]

    def multiplyMatrix(row1, col1, A, row2, col2, B):

    # Matrix to store the result

    C = [[0 for i in range(MAX)]

    for j in range(MAX)]

    # Check if multiplication is Possible

    if (row2 != col1):

    print(“Not Possible”)

    return

    # Multiply the two

    for i in range(row1):

    for y in range(col2):

    C[i][j] = 0

    for k in range(row2):

    C[i][j] += A[i][k] * B[k][j]

    # Print the result

    print(“Resultant Matrix: “)

    printMatrix(C, row1, col2)

    # Driver Code

    if __name__ == “__main__” :

    A = [[0 for i in range(MAX)]

    for j in range(MAX)]

    B = [[0 for i in range(MAX)]

    for j in range(MAX)]

    # Read size of Matrix A from user
    row1 = int(input(‘Enter the number of rows of First Matrix: ‘))
    col1 = int(input(“Enter the number of columns of First Matrix: “))

    # Read the elements of Matrix A from user
    print(“Enter the elements of First Matrix: “)

    for i in range(row1):
    for j in range(col1) :
    A[i][j] = int(input(“A[” + str(i) +”][” + str(j) + “]: “))

    # Read size of Matrix B from user
    row2 = int(input(“Enter the number of rows of Second Matrix: “))
    col2 = int(input(“Enter the number of columns of Second Matrix: “))

    # Read the elements of Matrix B from user.
    print(“Enter the elements of Second Matrix: “);

    for i in range(row2) :
    for j in range(col2) :
    B[i][j] = int(input(“B[” + str(i) +”][” + str(j) + “]: “))

    # Print the Matrix A
    print(“First Matrix: “)
    printMatrix(A, row1, col1)

    # Print the Matrix B
    print(“Second Matrix: “)
    printMatrix(B, row2, col2)

    # Find the product of the 2 matrices
    multiplyMatrix(row1, col1, A, row2, col2, B)

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky