Nonetype object is not callable ошибка

Добрый вечер.
Хотелось бы узнать, как избавиться от данной ошибки.

itemDesc.replace(';', '')

В этой строке возникает ошибка, в данной переменной находится html код.
Происходит ошибка:

TypeError: ‘NoneType’ object is not callable

  • python

angry's user avatar

angry

8,64717 золотых знаков73 серебряных знака180 бронзовых знаков

задан 6 окт 2011 в 14:01

xenoll's user avatar

xenollxenoll

4112 золотых знака7 серебряных знаков20 бронзовых знаков

2 ответа

ответ дан 6 окт 2011 в 16:28

Kanvi's user avatar

KanviKanvi

1561 серебряный знак5 бронзовых знаков

Уже разобрался, понимал, что нужно переменную объявить строкой, но вот такой вариант почему-то не работал

itemDesc = str(itemDesc)

Подсказали вот так:

itemDesc = itemDesc.__str__().replace('', '')<br>

Заработало.

angry's user avatar

angry

8,64717 золотых знаков73 серебряных знака180 бронзовых знаков

ответ дан 6 окт 2011 в 19:32

xenoll's user avatar

xenollxenoll

4112 золотых знака7 серебряных знаков20 бронзовых знаков

You will encounter the TypeError: ‘NoneType’ object is not callable if you try to call an object with a None value like a function. Only functions respond to function calls.

In this tutorial, we will look at examples of code that raise the TypeError and how to solve it.


Table of contents

  • TypeError: ‘nonetype’ object is not callable
  • Example #1: Printing Contents From a File
    • Solution
  • Example #2: Calling a Function Within a Function
    • Solution
  • Summary

TypeError: ‘nonetype’ object is not callable

Calling a function means the Python interpreter executes the code inside the function. In Python, we can only call functions. We can call functions by specifying the name of the function we want to use followed by a set of parentheses, for example, function_name(). Let’s look at an example of a working function that returns a string.

# Declare function

def simple_function():

    print("Hello World!")

# Call function

simple_function()
Hello World!

We declare a function called simple_function in the code, which prints a string. We can then call the function, and the Python interpreter executes the code inside simple_function().

None, string, tuple, or dictionary types do not respond to a function call because they are not functions. If you try to call a None value, the Python interpreter will raise the TypeError: ‘nonetype’ object is not callable.

Let’s look at examples of raising the error and how to solve them.

Example #1: Printing Contents From a File

Let’s look at an example of a program that reads a text file containing the names of famous people and prints the names out line by line.

The text file is called celeb_names.txt and contains the following names:

Leonardo DiCaprio

Michael Jordan

Franz Kafka

Mahatma Gandhi

Albert Einstein

The program declares a function that reads the file with the celebrity names.

# Declare function

def names():
    
    with open("celeb_names.txt", "r") as f:
        
        celebs = f.readlines()
        
        return celebs

The function opens the celeb_names.txt file in read-mode and reads the file’s contents into the celebs variable. We will initialize a variable to assign the celebrity names.

# Initialize variable 

names = None

We can then call our get_names() function to get the celebrity names then use a for loop to print each name to the console.

# Call function

names = names()

# For loop to print out names

for name in names:

    print(name)

Let’s see what happens when we try to run the code:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
1 names = names()

TypeError: 'NoneType' object is not callable

Unfortunately, we raise the NoneType object is not callable. This error occurs because we declared both a function and a variable with the same name. We declared the function first then the variable declaration overrides the function declaration. Any successive lines of code referring to names will refer to the variable, not the function.

Solution

We can either rename the function or the variable to solve this error. Adding a descriptive verb to a function name is a good way to differentiate from a variable name. Let’s change the function name from names() to get_names().

# Declare function with updated name

def get_names():

    with open("celeb_names.txt", "r") as f:

        celebs = f.readlines()

        return celebs

# Initialize variable with None

names = None

# Call function and store values in names variable

names = get_names()

# Loop over all names and print out

for name in names:

    print(name)

Renaming the function name means we will not override it when declaring the names variable. We can now run the code and see what happens.

Leonardo DiCaprio

Michael Jordan

Franz Kafka

Mahatma Gandhi

Albert Einstein

The code successfully works and prints out all of the celebrity names.

Alternatively, we could remove the initialization, as it is not required in Python. Let’s look at the revised code:

# Declare function with updated name

def get_names():

    with open("celeb_names.txt", "r") as f:

        celebs = f.readlines()

        return celebs

# Call function and store values in names variable without initializing

names = get_names()

# Loop over all names and print out

for name in names:

    print(name)
Leonardo DiCaprio

Michael Jordan

Franz Kafka

Mahatma Gandhi

Albert Einstein

Example #2: Calling a Function Within a Function

Let’s look at an example of two functions; one function executes a print statement, and the second function repeats the call to the first function n times.

def hello_world():

    print("Hello World!")

def recursive(func, n): # Repeat func n times

    if n == 0:

        return
    
    else:
        
        func()
        
        recursive(func, n-1)

Let’s see what happens when we try to pass the call to the function hello_world() to the recursive() function.

recursive(hello_world(), 5)
TypeError                                 Traceback (most recent call last)
      1 recursive(hello_world(), 5)

      3         return
      4     else:
      5         func()
      6         recursive(func, n-1)
      7 

TypeError: 'NoneType' object is not callable

Solution

To solve this error, we need to pass the function object to the recursive() function, not the result of a call to hello_world(), which is None since hello_world() does not return anything. Let’s look at the corrected example:

recursive(hello_world, 5)

Let’s run the code to see the result:

Hello World!

Hello World!

Hello World!

Hello World!

Hello World!

Summary

Congratulations on reading to the end of this tutorial. To summarize, TypeError’ nonetype’ object is not callable occurs when you try to call a None type value as if it were a function. TypeErrors happen when you attempt to perform an illegal operation for a specific data type. To solve this error, keep variable and function names distinct. If you are calling a function within a function, make sure you pass the function object and not the result of the function if it returns None.

For further reading on not callable TypeErrors, go to the articles:

  • How to Solve Python TypeError: ‘tuple’ object is not callable.
  • How to Solve Python TypeError: ‘bool’ object is not callable.
  • How to Solve Python TypeError: ‘_io.TextIOWrapper’ object is not callable.

To learn more about Python, specifically for data science and machine learning, go to the online courses page on Python.

Have fun and happy researching!

In Python, a specific data type referred to as “NoneType” is used to store “None” value. Python uses the keyword “None” to store the “Null/None” value in a variable. Some functions in Python also return the “None” value, such as the sort() function.

While dealing with a “None” value, “TypeError: NoneType object is not callable” may occur in Python. To resolve this error, various solutions are provided by Python.

This blog will provide a comprehensive guide on resolving the “TypeError: NoneType object is not callable” in Python. This guide contains the following contents:

  • Reason 1: Using the Same Name for Function and Variable
  • Solution: Rename Variable or Function
  • Reason 2: Class Methods and Class Properties Have the Same Name
  • Solution: Rename the Class Method or Class Attributes
  • Reason 3: Calling None Variable as a Function
  • Solution: Removing Parentheses

So, let’s get started!

Reason 1: Using the Same Name for Function and Variable

This “TypeError” occurs when we try to use the same name for a function and variable in a Python program. Here is an example:

The above output shows the “TypeError” because the function “sample” and variable “sample” are initialized with the same name in a program.

Solution: Rename Variable or Function

To fix this error, make sure to rename the function or variable in a program. After renaming the function or variable, re-execute the program to remove the error.

Code:

def sample1():
    return 'True'
sample = None
print(sample1())

In the above code, the user-defined function is renamed from “sample” into “sample1”. After renaming the function name, the function value will be accessed using parentheses.

Output:

The above output verified that the function returns a “None” value.

Reason 2: Class Methods and Class Properties Have the Same Name

The other prominent reason which produces this error in the program is when the user uses the same name for the class property and class method. Here is an example:

The above output, the class method “example”, and the class property/attribute “self.example” have the same name in a program.

Solution: Rename the Class Method or Class Attributes

To rectify this error, rename the method of the class and re-execute the Python script. Here’s an example:

Code:

class sample():
    def __init__(self):
        self.example = None
       
    def value(self):
        return "True"
   
smp = sample()
print(smp.value())

In the above code, the class method name “example” is renamed to “value”. After renaming the method, the program runs successfully without any errors.

Output:

The above output verified that the class method executes the program successfully.

Reason 3: Calling None Variable as a Function

The error also arises when the user calls the none value as if it were a function in a Python program. Below is an example of this error:

The above output displays the “TypeError” because the none value variable is called as a function in Python.

Solution: Removing Parentheses

To resolve this error, you need to remove the parentheses or correct the assignment. Let’s look at the below solutions code:

Code:

value = None
print(value)

In the above code, the “None” value is assigned to the variable “value” in the program. The value is displayed on the screen using the “print()” function.

Output:

This output displays the value of the variable “value“.

Conclusion

The “TypeError: NoneType object is not callable” arises in Python when we try to access a “None” variable as a Function or use the same name for a variable and function, etc. To resolve this error, various solutions are provided, such as renaming functions or variables, renaming class methods, and removing parentheses while accessing variables. This Python article has presented a detailed guide on resolving the “NoneType object is not callable” error using appropriate examples.

When we call the object having the value None, we might encounter TypeError: ‘nonetype’ object is not callable.

In this guide, we will deal with this error, why it occurs, and what it means.

Apart from that, we have example codes, and scenarios to help you understand the error and solve it quickly in your program.

When working with Python, Nonetype data type is used to store the None value.

Additionally, the keyword None is used to store the value none/null in a variable.

Now let’s understand why we get Typeerror: nonetype object is not callable.

The Typeerror: nonetype object is not a callable error occurs if we call the None value as if it is a function.

To fix it, find where the values come from, hence correct the assignment, or get rid of the parenthesis.

Common Causes of ‘nonetype’ object is not callable

The common causes of this error include the following:

  1. Calling the None value inside the parenthesis as if it is a function.
  2. Having the same name for a variable and a function.
  3. Trying to call the function twice that returns twice.
  4. The calls method and class property have the same name.
  5. By mistake overriding the built-in function and setting it to None.

Example Scenario of nonetype object is not callable

Certainly, here is an example scenario of how this error occurs:

def get_name():
    return None

name = get_name()
print(name())

In our example code, the get_name() function returns None, which means that the name variable will also have a value of None.

When we try to call name() in the print statement, we are essentially trying to call None as if it were a function.

Wherein it is not possible and will result in the “Typeerror: nonetype object is not callable” error message.

Now that you know how possibly it occurs, let’s fix it in the next section.

How to fix typeerror: ‘nonetype’ object is not callable

Here are the following solutions you can use depending on the cause of the error.

1. Rename the method of the Class

One of the causes of the error is having the same name of the class method and class property.

Take a look at this code snippet where it triggers the error:

class MyExample():
    def __init__(self):
        self.name = None

    def name(self):
        return self.name

ex1 = MyExample()

# TypeError: 'NoneType' object is not callable
print(ex1.name())

As you can see in the code Myexample have the same name on the attribute.

In which the attributes hide the method, so when the instance of the class is called in the method…

We trigger the error.

To fix the error make sure to change the name of the method of a class.

class MyExample():
    def __init__(self):
        self.name = None

    def get_name(self):
        return self.name

ex1 = MyExample()

print(ex1.get_name())  # returns None

Expected output:

None

2. Function and a variable with the same name

Another way to fix the error is to avoid having the same name on a function and variable.

Take a look at the example code below:

def example():
    return 'I love itsourcecode'

example = None

# TypeError: 'NoneType' object is not callable
example()

Output:

Traceback (most recent call last):
  File "C:\Users\Windows\PycharmProjects\pythonProject\main.py", line 7, in <module>
    example()
TypeError: 'NoneType' object is not callable

Having the same name in function and variable shadow the function set to None.

Wherein every time we call the function, we end up calling the variable.

Here is an example snippet code that fixed the error:

def Myexample():
    return 'I love itsourcecode'

My_var = None

print(Myexample())  # I love itsourcecode

Expected Output:

I love itsourcecode

Another cause of the error is having an extra parenthesis.

Examine the example error code below.

def example(x):
    x()

def another_func():
    print('I love itsourcecode')


# TypeError: 'NoneType' object is not callable
example(another_func())

The example function takes another function as an argument and calls it.

However, notice that we called the other function when passing it to example.

The function returns None, so the example function got called with a None value.

To fix the error we need to remove the extra parenthesis to call the example function.

def example(x):
    x()


def another_func():
    print('I love itsourcecode')


example(another_func)  # I love itsourcecode

Expected output:

I love itsourcecode

Now the example function gets called with a function that invokes it and prints the message.

4. Check the return value of the method before calling it

Check the return value of the method before calling it. We can modify the method to return a lambda function that returns None.

Example error code:

class MyClass:
    def my_method(self):
        return None

my_obj = MyClass()
result = my_obj.my_method()()
print(result)

Output

TypeError: 'NoneType' object is not callable

To fix this we should modify the method to return lambda function that returns None.

Here is the snippet code:

class MyClass:
    def my_method(self):
        return lambda: None

my_obj = MyClass()
result = my_obj.my_method()()
print(result)

Output:

None

Conclusion

In conclusion, in fixing TypeError: ‘NoneType’ object is not callableerror we take note of the following:

  • Avoid having the same name on a function and a variable.
  • Avoid having the same name on the class method and property.
  • Do not call a None value with parentheses ().
  • Do not override a built-in function and set it to None.
  • Do not call a function that returns None twice.

If you are finding solutions to some errors you might encounter we also have Typeerror object of type float32 is not json serializable.

Thank you for reading!

Ad

At Career Karma, our mission is to empower users to make confident decisions by providing a trustworthy and free directory of bootcamps and career resources. We believe in transparency and want to ensure that our users are aware of how we generate revenue to support our platform.

Career Karma recieves compensation from our bootcamp partners who are thoroughly vetted before being featured on our website. This commission is reinvested into growing the community to provide coaching at zero cost to their members.

It is important to note that our partnership agreements have no influence on our reviews, recommendations, or the rankings of the programs and services we feature. We remain committed to delivering objective and unbiased information to our users.

In our bootcamp directory, reviews are purely user-generated, based on the experiences and feedback shared by individuals who have attended the bootcamps. We believe that user-generated reviews offer valuable insights and diverse perspectives, helping our users make informed decisions about their educational and career journeys.

Find the right bootcamp for you

ck-logo

X

By continuing you agree to our
Terms of Service and Privacy Policy, and you consent to
receive offers and opportunities from Career Karma by telephone, text message, and email.

Понравилась статья? Поделить с друзьями:
  • Nonetype object has no attribute append ошибка
  • None ошибка python
  • Nothing here ошибка
  • Notepad поиск ошибок
  • Notepad ошибка при сохранении файла