Str object is not callable ошибка

Every programming language has certain keywords with specific, prebuilt functionalities and meanings. Naming your variables or functions after these keywords is most likely going to raise an error. We'll discuss one of these cases in this article — the TypeError: 'str' object is not callable error in Python. The TypeError: 'str' object is not callable error mainly occurs when: * You pass a variable named str as a parameter to the str() function. * When you call a string like a function.

Typeerror: str object is not callable – How to Fix in Python

Every programming language has certain keywords with specific, prebuilt functionalities and meanings.

Naming your variables or functions after these keywords is most likely going to raise an error. We’ll discuss one of these cases in this article — the TypeError: 'str' object is not callable error in Python.

The TypeError: 'str' object is not callable error mainly occurs when:

  • You pass a variable named str as a parameter to the str() function.
  • When you call a string like a function.

In the sections that follow, you’ll see code examples that raise the TypeError: 'str' object is not callable error, and how to fix them.

Example #1 – What Will Happen If You Use str as a Variable Name in Python?

In this section, you’ll see what happens when you used a variable named str as the str() function’s parameter.

The str() function is used to convert certain values into a string. str(10) converts the integer 10 to a string.

Here’s the first code example:

str = "Hello World"

print(str(str))
# TypeError: 'str' object is not callable

In the code above, we created a variable str with a value of «Hello World». We passed the variable as a parameter to the str() function.

The result was the TypeError: 'str' object is not callable error. This is happening because we are using a variable name that the compiler already recognizes as something different.

To fix this, you can rename the variable to a something that isn’t a predefined keyword in Python.

Here’s a quick fix to the problem:

greetings = "Hello World"

print(str(greetings))
# Hello World

Now the code works perfectly.

Example #2 – What Will Happen If You Call a String Like a Function in Python?

Calling a string as though it is a function in Python will raise the TypeError: 'str' object is not callable error.

Here’s an example:

greetings = "Hello World"

print(greetings())
# TypeError: 'str' object is not callable

In the example above, we created a variable called greetings.

While printing it to the console, we used parentheses after the variable name – a syntax used when invoking a function: greetings().

This resulted in the compiler throwing the TypeError: 'str' object is not callable error.

You can easily fix this by removing the parentheses.

This is the same for every other data type that isn’t a function. Attaching parentheses to them will raise the same error.

So our code should work like this:

greetings = "Hello World"

print(greetings)
# Hello World

Summary

In this article, we talked about the TypeError: 'str' object is not callable error in Python.

We talked about why this error might occur and how to fix it.

To avoid getting this error in your code, you should:

  • Avoid naming your variables after keywords built into Python.
  • Never call your variables like functions by adding parentheses to them.

Happy coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

So you have encountered the exception, i.e., TypeError: ‘str’ object is not callable. In the following article, we will discuss type errors, how they occur and how to resolve them.

What is a TypeError?

The TypeError occurs when you try to operate on a value that does not support that operation. The most common reason for an error in a Python program is when a certain statement is not in accordance with the prescribed usage. The Python interpreter immediately raises a type error when it encounters an error, usually along with an explanation. For instance:

val1 = 100
val2 = "random text"

print(val1/val2)

When you try to divide an integer value with a string, it results in a type error.

TypeError Example

TypeError Example

Like any TypeError, the ‘str’ object is not callable occurs when we try to perform an operation not supported by that datatype. In our case, here it’s the ‘string’ datatype. Let’s see some examples of where it can occur and how we can resolve them.

Example 1:

str = "This is text number 1"
string2 = "This is text number 2"

print(str(str) + string2)

In the code above, we have deliberately defined the first variable name with a reserved keyword called str. Moreover, the second variable, string2, follows Python’s naming conventions. In the print statement, we use the str method on the str variable, this confuses the Python’s interpreter, and it raises a type error, as shown in the image below.

The output of example 1

The output of example 1

Example 2:

string1 = "This is text number 1"
string2 = "This is text number 2"

print("%s %s" (string1,string2))

Contrary to example 1, where we had defined a variable with the str reserved keyword, which raised an error. In the example 2 code, we are using the ‘ % ‘ operator to perform string formatting. However, there is a minor issue in the syntax. We have omitted the % before the tuple. Missing this symbol can raise a similar error.

The output of example 2

The output of example 2

How to resolve this error?

The solution to example 1:

In Python, the str() function converts values into a string. It takes an object as an argument and converts it into a string. The str is a pre-defined function and also a reserved keyword. Therefore, it can’t be used as a variable name as per Python’s naming conventions.

To resolve the error, use another variable name.

string1 = "This is text number 1"
string2 = "This is text number 2"

print(str(string1) + string2)

Using proper naming convention, error gets resolved.

Using proper naming convention, the error gets resolved.

The solution to example 2:

In example 2, we tried to use string formatting to display string1 and string2 together. However, not using the % operator before the tuples of values TypeError: ‘str’ object is not a callable error that gets thrown. To resolve it, use the % operator in its proper place.

string1 = "This is text number 1"
string2 = "This is text number 2"

print("%s %s" %(string1,string2))

Using the % operator at its right place resolves the error

Using the % operator in its right place resolves the error

TypeError: ‘str’ object is not callable Selenium

This error is likely due to accidentally invoking a function() which is actually a property. Please check your code for this.

TypeError ‘str’ object is not callable BeautifulSoup/Django/Collab

Irrespective of the library used, this error can creep in if you have used some reserved keyword as a variable or redefined some property or a function of the library. Please check your code for such things.

TypeError ‘str’ object is not callable matplotlib

Somewhere in the code, you might have used plt.xlabel = “Some Label”. This will change the import of matplotlib.pyplot. Try to close the Notebook and restart your Kernel. After the restart, rerun your code, and everything should be fine.

FAQs

How do I fix the str object that is not callable?

To fix this error, you need to ensure that no variable is named after the str reserved keyword. Change it if this is the case.

What does str object is not callable mean?

TypeError generally occurs if an improper naming convention has been used, in other words, if the str keyword is used as a variable name.

TypeError ‘str’ object is not callable pyspark

This error is likely due to accidentally overwriting one of the PySpark functions with a string. Please check your code for this.

Conclusion

In this article, we discussed where the ‘str’ object is not callable error can occur and how we can resolve it. This is an easy error to fix. We must ensure we don’t use the reserved keywords for naming variables. In addition, we also have to avoid redefining default methods.

Trending Python Articles

  • “Other Commands Don’t Work After on_message” in Discord Bots

    “Other Commands Don’t Work After on_message” in Discord Bots

    February 5, 2023

  • Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    by Rahul Kumar YadavFebruary 5, 2023

  • [Resolved] NameError: Name _mysql is Not Defined

    [Resolved] NameError: Name _mysql is Not Defined

    by Rahul Kumar YadavFebruary 5, 2023

  • Best Ways to Implement Regex New Line in Python

    Best Ways to Implement Regex New Line in Python

    by Rahul Kumar YadavFebruary 5, 2023

Table of Contents
Hide
  1. What is typeerror: ‘str’ object is not callable in Python?
  2. Scenario 1 – Declaring a variable name called “str”
  3. Solving typeerror: ‘str’ object is not callable in Python.
  4. Scenario 2 – String Formatting Using %

One of the most common errors in Python programming is typeerror: ‘str’ object is not callable, and sometimes it will be painful to debug or find why this issue appeared in the first place.

Python has a built-in method str() which converts a specified value into a string. The str() method takes an object as an argument and converts it into a string.

Since str() is a predefined function and a built-in reserved keyword in Python, you cannot use it in declaring it as a variable name or a function name. If you do so, Python will throw a typeerror: ‘str‘ object is not callable.

Let us take a look at few scenarios where you could reproduce this error.

Scenario 1 – Declaring a variable name called “str”

The most common scenario and a mistake made by developers are declaring a variable named ‘str‘ and accessing it. Let’s look at a few examples of how to reproduce the ‘str’ object is not callable error.

str = "Hello, "
text = " Welcome to ItsMyCode"

print(str(str + text))

# Output
Traceback (most recent call last):
  File "c:ProjectsTryoutslistindexerror.py", line 4, in <module>
    print(str(str + text))
TypeError: 'str' object is not callable

In this example, we have declared ‘str‘ as a variable, and we are also using the predefined str() method to concatenate the string.

str = "The cost of apple is "
x = 200
price= str(x)
print((str + price))

# output
Traceback (most recent call last):
  File "c:ProjectsTryoutslistindexerror.py", line 3, in <module>
    price= str(x)
TypeError: 'str' object is not callable

The above code is similar to example 1, where we try to convert integer x into a string. Since str is declared as a variable and if you str() method to convert into a string, you will get object not callable error.

Solving typeerror: ‘str’ object is not callable in Python.

Now the solution for both the above examples is straightforward; instead of declaring a variable name like “str” and using it as a function, declare a more meaningful name as shown below and make sure that you don’t have “str” as a variable name in your code.

text1 = "Hello, "
text2 = " Welcome to ItsMyCode"

print(str(text1 + text2))

# Output
Hello,  Welcome to ItsMyCode
text = "The cost of apple is "
x = 200
price= str(x)
print((text + price))

# Output
The cost of apple is 200

Scenario 2 – String Formatting Using %

Another hard-to-spot error that you can come across is missing the % character in an attempt to append values during string formatting.

If you look at the below code, we have forgotten the string formatting % to separate our string and the values we want to concatenate into our final string. 

print("Hello %s its %s day"("World","a beautiful"))

# Output 
Traceback (most recent call last):
  File "c:ProjectsTryoutslistindexerror.py", line 1, in <module>
    print("Hello %s its %s day"("World","a beautiful"))
TypeError: 'str' object is not callable

print("Hello %s its %s day"%("World","a beautiful"))

# Output
Hello World its a beautiful day

In order to resolve the issue, add the % operator before replacing the values ("World","a beautiful") as shown above.

Ezoic

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

This error occurs when you try to call a string as if it were a function. This error can occur if you override the built-in str() function or you try to access elements in a string using parentheses instead of square brackets.

You can solve this error by ensuring you do not override the str() function or any function names. For example:

my_str = 'Python is fun!'

my_int = 15

my_int_as_str = str(15)

If you want to access elements in a string, use square brackets. For example,

my_str = 'Python is fun!'

first_char = my_str[0]

This tutorial will go through the error in detail, and we will go through an example to learn how to solve the error.

Table of contents

  • TypeError: ‘str’ object is not callable
    • What is a TypeError?
    • What does Callable Mean?
  • Example #1: Using Parenthesis to Index a String
    • Solution
  • Example #2: String Formatting Using
    • Solution
  • Example #3: Using the Variable Name “str”
    • Solution
  • Summary

TypeError: ‘str’ object is not callable

What is a TypeError?

TypeError tells us that we are trying to perform an illegal operation for a specific Python data type.

What does Callable Mean?

Callable objects in Python have the __call__ method. We call an object using parentheses. To verify if an object is callable, you can use the callable() built-in function and pass the object to it. If the function returns True, the object is callable, and if it returns False, the object is not callable.

Let’s test the callable() built-in function with a string:

string = "research scientist"

print(callable(string))
False

We see that callable returns false on the string.

Let’s test the callable() function with the square root method from the math module:

from math import sqrt

print(callable(sqrt))
True

We see that callable returns True on the sqrt method. All methods and functions are callable objects.

If we try to call a string as if it were a function or a method, we will raise the error “TypeError: ‘str’ object is not callable.”

Example #1: Using Parenthesis to Index a String

Let’s look at an example of a program where we define a for loop over a string:

string = "research scientist"

for i in range(len(string)):

    print(string(i))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      1 for i in range(len(string)):
      2     print(string(i))
      3 

TypeError: 'str' object is not callable

To index a string, you have to use square brackets. If you use parentheses, the Python interpreter will treat the string as a callable object. Strings are not callable. Therefore you will raise the error “TypeError: ‘str’ object is not callable”.

Solution

We need to replace the parentheses with square brackets to solve this error.

string = "research scientist"

for i in range(len(string)):

    print(string[i])
r
e
s
e
a
r
c
h
 
s
c
i
e
n
t
i
s
t

The code runs with no error and prints out each character in the string.

Example #2: String Formatting Using

The TypeError can also occur through a mistake in string formatting. Let’s look at a program that takes input from a user. This input is the price of an item in a store with a seasonal discount of 10%. We assign the input to the variable price_of_item. Then we calculate the discounted price. Finally, we can print out the original price and the discounted price using string formatting.

price_of_item = float(input("Enter the price of the item"))

discount_amount = 0.1

discounted_price = price_of_item - (price_of_item * discount_amount)

rounded_discounted_price = round(discounted_price,2)

print('The original price was %s, the price after the discount is %s'(price_of_item, rounded_discounted_price))

With string formatting, we can replace the %s symbols with the values price_of_item and rounded_discounted_price. Let’s see what happens when we try to run the program.

Enter the price of the item17.99

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
1 print('The original price was %s, the price after the discount is %s'(price_of_item, rounded_discounted_price))

TypeError: 'str' object is not callable

The code returns an error because we forgot to include the % operator to separate the string and the values we want to add to the string. The Python interpreter tries to call ‘The original price was %s, the price after 10% discount is %s‘ because the string has parentheses following it.

Solution

To solve this error, we need to add the % between the string

‘The original price was %s, the price after the discount is %s‘ and (price_of_item, rounded_discounted_price)

price_of_item = float(input("Enter the price of the item"))

discount_amount = 0.1

discounted_price = price_of_item - (price_of_item * discount_amount)

rounded_discounted_price = round(discounted_price,2)

print('The original price was %s, the price after the discount is %s'%(price_of_item, rounded_discounted_price))
Enter the price of the item17.99

The original price was 17.99, the price after the discount is 16.19

The code successfully prints the original price and the rounded price to two decimal places.

Example #3: Using the Variable Name “str”

Let’s write a program that determines if a user is too young to drive. First, we will collect the current age of the user using an input() statement. If the age is above 18, the program prints that the user is old enough to drive. Otherwise, we calculate how many years are left until the user can drive. We use the int() method to convert the age to an integer and then subtract it from 18.

Next, we convert the value to a string to print to the console. We convert the value to a string because we need to concatenate it to a string.

str = input("What is your age? ")

if int(str) >= 18:

    print('You are old enough to drive!')

else:

    years_left = 18 - int(str)

    years_left = str(years_left)

    print('You are not old enough to drive, you have ' + years_left + ' year(s) left')


Let’s see what happens when we run the program:

What is your age? 17

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      3 else:
      4     years_left = 18 - int(str)
      5     years_left = str(years_left)
      6     print('You are not old enough to drive, you have ' + years_left + ' year(s) left')
      7 

TypeError: 'str' object is not callable

We raise the error “TypeError: ‘str’ object is not callable” because we tried to use the str() method to convert the integer value years_left. However, earlier in the program we declared a variable called “str“. From that point on, the Python interpreter sees “str” as a string in the program and not a function. Therefore, when we try to call str() we are instead trying to call a string.

Solution

To solve this error, we need to rename the user input to a suitable name that describes the input. In this case, we can use “age“.

age = input("What is your age? ")

if int(age) >= 18:

    print('You are old enough to drive!')

else:

    years_left = 18 - int(age)

    years_left = str(years_left)

    print('You are not old enough to drive, you have ' + years_left + 'year(s) left')

Now we have renamed the variable, we can safely call the str() function. Let’s run the program again to test the outcome.

What is your age? 17

You are not old enough to drive, you have 1 year(s) left

The code runs and tells the user they have 1 year left until they can drive.

Summary

Congratulations on reading to the end of this tutorial!

For further reading on the ‘not callable’ TypeError, go to the article: How to Solve Python TypeError: ‘module’ object is not callable.

Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.

Have fun and happy researching!

Have you ever seen the TypeError object is not callable when running one of your Python programs? We will find out together why it occurs.

The TypeError object is not callable is raised by the Python interpreter when an object that is not callable gets called using parentheses. This can occur, for example, if by mistake you try to access elements of a list by using parentheses instead of square brackets.

I will show you some scenarios where this exception occurs and also what you have to do to fix this error.

Let’s find the error!

What Does Object is Not Callable Mean?

To understand what “object is not callable” means we first have understand what is a callable in Python.

As the word callable says, a callable object is an object that can be called. To verify if an object is callable you can use the callable() built-in function and pass an object to it. If this function returns True the object is callable, if it returns False the object is not callable.

callable(object)

Let’s test this function with few Python objects…

Lists are not callable

>>> numbers = [1, 2, 3]
>>> callable(numbers)
False

Tuples are not callable

>>> numbers = (1, 2, 3)
>>> callable(numbers)
False

Lambdas are callable

>>> callable(lambda x: x+1)
True

Functions are callable

>>> def calculate_sum(x, y):
...     return x+y
... 
>>> callable(calculate_sum)
True

A pattern is becoming obvious, functions are callable objects while data types are not. And this makes sense considering that we “call” functions in our code all the time.

What Does TypeError: ‘int’ object is not callable Mean?

In the same way we have done before, let’s verify if integers are callable by using the callable() built-in function.

>>> number = 10
>>> callable(number)
False

As expected integers are not callable 🙂

So, in what kind of scenario can this error occur with integers?

Create a class called Person. This class has a single integer attribute called age.

class Person:
    def __init__(self, age):
        self.age = age

Now, create an object of type Person:

john = Person(25)

Below you can see the only attribute of the object:

print(john.__dict__)
{'age': 25}

Let’s say we want to access the value of John’s age.

For some reason the class does not provide a getter so we try to access the age attribute.

>>> print(john.age())
Traceback (most recent call last):
  File "callable.py", line 6, in <module>
    print(john.age())
TypeError: 'int' object is not callable

The Python interpreter raises the TypeError exception object is not callable.

Can you see why?

That’s because we have tried to access the age attribute with parentheses.

The TypeError‘int’ object is not callable occurs when in the code you try to access an integer by using parentheses. Parentheses can only be used with callable objects like functions.

What Does TypeError: ‘float’ object is not callable Mean?

The Python math library allows to retrieve the value of Pi by using the constant math.pi.

I want to write a simple if else statement that verifies if a number is smaller or bigger than Pi.

import math

number = float(input("Please insert a number: "))

if number < math.pi():
    print("The number is smaller than Pi")
else:
    print("The number is bigger than Pi")

Let’s execute the program:

Please insert a number: 4
Traceback (most recent call last):
  File "callable.py", line 12, in <module>
    if number < math.pi():
TypeError: 'float' object is not callable

Interesting, something in the if condition is causing the error ‘float’ object is not callable.

Why?!?

That’s because math.pi is a float and to access it we don’t need parentheses. Parentheses are only required for callable objects and float objects are not callable.

>>> callable(4.0)
False

The TypeError‘float’ object is not callable is raised by the Python interpreter if you access a float number with parentheses. Parentheses can only be used with callable objects.

What is the Meaning of TypeError: ‘str’ object is not callable?

The Python sys module allows to get the version of your Python interpreter.

Let’s see how…

>>> import sys
>>> print(sys.version())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

No way, theobject is not callable error again!

Why?

To understand why check the official Python documentation for sys.version.

Python sys version

That’s why!

We have added parentheses at the end of sys.version but this object is a string and a string is not callable.

>>> callable("Python")
False

The TypeError‘str’ object is not callable occurs when you access a string by using parentheses. Parentheses are only applicable to callable objects like functions.

Error ‘list’ object is not callable when working with a List

Define the following list of cities:

>>> cities = ['Paris', 'Rome', 'Warsaw', 'New York']

Now access the first element in this list:

>>> print(cities(0))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable

What happened?!?

By mistake I have used parentheses to access the first element of the list.

To access an element of a list the name of the list has to be followed by square brackets. Within square brackets you specify the index of the element to access.

So, the problem here is that instead of using square brackets I have used parentheses.

Let’s fix our code:

>>> print(cities[0])
Paris

Nice, it works fine now.

The TypeError‘list’ object is not callable occurs when you access an item of a list by using parentheses. Parentheses are only applicable to callable objects like functions. To access elements in a list you have to use square brackets instead.

Error ‘list’ object is not callable with a List Comprehension

When working with list comprehensions you might have also seen the “object is not callable” error.

This is a potential scenario when this could happen.

I have created a list of lists variable called matrix and I want to double every number in the matrix.

>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [[2*row(index) for index in range(len(row))] for row in matrix]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
  File "<stdin>", line 1, in <listcomp>
TypeError: 'list' object is not callable

This error is more difficult to spot when working with list comprehensions as opposed as when working with lists.

That’s because a list comprehension is written on a single line and includes multiple parentheses and square brackets.

If you look at the code closely you will notice that the issue is caused by the fact that in row(index) we are using parentheses instead of square brackets.

This is the correct code:

>>> [[2*row[index] for index in range(len(row))] for row in matrix]
[[2, 4, 6], [8, 10, 12], [14, 16, 18]]

Conclusion

Now that we went through few scenarios in which the errorobject is not callable can occur you should be able to fix it quickly if it occurs in your programs.

I hope this article has helped you save some time! 🙂

Related posts:

I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

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:Python37libsocket.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'>

Понравилась статья? Поделить с друзьями:
  • Str object has no attribute append как исправить
  • Str not found mount and blade warband как исправить
  • Str error python
  • Stp drop d link error
  • Storwize v3700 error 578