Nonetype object is not callable ошибка

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

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 to call a function, we use the function name followed by the parenthesis

()

. But if we try to call other Python objects like,

int

,

list

,

str

,

tuple

, etc., using parenthesis, we receive the TypeError Exception with an error message that the following object is not callable.


None

is a reserved keyword value in Python, which data type is

NoneType

. If we put parenthesis »

()

» after a None value and try to call it as a function we receive the

TypeError: 'NoneType' object is not callable

Error.

In this Python guide, we will walk through this Python error and discuss why it occurs in Python and how to solve it. We will also discuss a common example scenario where many Python learners commit mistakes while writing the program and encounter this error.

So let’s get started with the Error Statement!

The

TypeError: 'NoneType' object is not callable

is a  standard Python error statement and like other error statements, it can be divided into two parts.


  1. Exception Type


    TypeError



  2. Error Message (


    'NoneType' object is not callable


    )


1. TypeError

TypeError is a standard Python exception, it occurs in a Python program when we perform an unsupportable operation on a specific Python object. For instance, integer objects do not support indexing in Python. And if we try to perform indexing on an integer object, we also receive the


TypeError


with some error message.


2. ‘NoneType’ object is not callable

«NoneType object is not callable» is an error message, and it is raised in the program when we try to call a NoneType object as a function. There is only one NoneType object value in Python

None

# None Value
obj = None

print('Type of obj is: ',type(obj))


Output

Type of obj is: <class 'NoneType'>

And if we try to call the None value objects or variables as a function using parenthesis () we receive the TypeError with the message ‘NoneType’ object is not callable’


Example

# None Value
obj = None

# call None obj as a function 
obj()


Output

Traceback (most recent call last):
  File "main.py", line 5, in 
    obj()
TypeError: 'NoneType' object is not callable

In this example, we tried to call the

obj

variable as a function

obj()

and we received the Error. The value of

obj

is

None

which make the

obj

a

NoneType

object, and we can not perform function calling on a NoneType object. When the Python interpreter read the statement

obj()

, it tried to call the obj as a function, but soon it realised that

obj

is not a function and the interpreter threw the error.

Common Example Scenario

The most common example where many Python learners encounter this error is when they use the same name for a function and a None Type variable. None value is mostly used to define an initial value, and if we define a function as the same name of the variable with None value we will receive this error in our Program.


Example

Let’s create a Python function

result()

that accepts a list of paired tuples

students [(name,marks)]

and return the name and the marks of the student who get the maximum marks.

def result(students):
    # initilize the highest_marks
    highest_marks = 0

    for name, marks in students:
        if marks> highest_marks:
            rank1_name = name
            highest_marks =marks

    return (rank1_name, highest_marks)

students = [("Aditi Musunur", 973),
            ("Amrish Ilyas", 963),
            ("Aprativirya Seshan", 900),
            ("Debasis Sundhararajan", 904),
            ("Dhritiman Salim",978) ]

# initial result value
result = None

# call the result function
result = result(students)

print(f"The Rank 1 Student is {result[0]} with {result[1]} marks")


Output

Traceback (most recent call last):
  File "main.py", line 22, in 
    result = result(students)
TypeError: 'NoneType' object is not callable


Break the code

In this example, we are getting the error in 22 with

result = result(students)

statement. This is because at that point result is not a function name but a

None

value variable. Just above the function calling statement, we have defined the

result

value as None using the

result = None

statement.

As Python executes its code from top to bottom the value of the

result

object changed from

function

to

None

when we define the

result

initial value after the function definition. And the Python interpreter calls the None object as a function when it interprets the

result()

statement.


Solution

The solution to the above problem is straightforward. When writing a Python program we should always consider using the different names for functions and value identifiers or variables. To solve the above problem all we need to do is define a different name for the result variable that we used to store the return value of the result function.

def result(students):
    # initilize the highest_marks
    highest_marks = 0

    for name, marks in students:
        if marks> highest_marks:
            rank1_name = name
            highest_marks =marks

    return (rank1_name, highest_marks)

students = [("Aditi Musunur", 973),
            ("Amrish Ilyas", 963),
            ("Aprativirya Seshan", 900),
            ("Debasis Sundhararajan", 904),
            ("Dhritiman Salim",978) ]

# initialize the initial value
rank1= None

# call the result function
rank1 = result(students)

print(f"The Rank 1 Student is {rank1[0]} with {rank1[1]} marks")


Output

The Rank 1 Student is Dhritiman Salim with 978 marks


Conclusion

In this Python error tutorial, we discussed

TypeError: 'NoneType' object is not callable

Error, and learn why this error occurs in Python and how to debug it. You will only encounter this error in your Python program when you try to call a None object as a function. To debug this error you carefully need to read the error and go through the code again and look for the line which is causing this error.

With some practice, you will be able to solve this error in your program in no time. If you are still getting this error in your Python program, you can share the code in the comment section. We will try to help you in debugging.


People are also reading:

  • Python Subdomain Scanner

  • WiFi Scanner in Python

  • How to create Logs in Python?

  • Python Data Structure

  • Best Way to Learn Python

  • Python vs PHP

  • Best Python Books

  • Best Python Interpreters

  • Python Multiple Inheritance

  • Class and Objects in Python

Objects with the value None cannot be called. This is because None values are not associated with a function. If you try to call an object with the value None, you’ll encounter the error “TypeError: ‘nonetype’ object is not callable”.

In this guide, we discuss why this error is raised and what it means. We’ll walk through an example of this error to help you understand how you can solve it in your program.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

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.

TypeError: ‘nonetype’ object is not callable

When you call a function, the code inside the function is executed by the Python interpreter.

Only functions can be called. To call a function, you need to specify the name of a function, followed by a set of parentheses. Those parenthesis can optionally contain arguments that are passed through to a function.

Consider the following code:

def show_languages():
	print("Python, Java, C, C++")

show_languages()

First, declare a function called “show_languages”.

On the last line of our code, we call our function. This executes all the code in the block where we declare the “show_languages” function.

Similar to how you cannot call a string, a tuple, or a dictionary, you cannot call a None value. These data types do not respond to a function call because they are not functions. The result of calling a None value is always “TypeError: ‘nonetype’ object is not callable”. 

An Example Scenario

Let’s build a program that reads a file with a leaderboard for a poker tournament and prints out each player’s position on the leaderboard to the console.

We have a file called poker.txt which contains the following:

1: Greg Daniels
2: Lucy Scott
3: Hardy Graham
4: Jenny Carlton
5: Hunter Patterson

We start by writing a function that reads the file with leaderboard information:

def tournament_results():
	with open("poker.txt", "r") as file:
		tournament = file.readlines()
		return tournament

This function opens the “poker.txt” file in read mode and reads its contents into a variable called “tournament”. We return this variable to the main program.

Until we call our function, “tournament_results” will not have a value. So, we’re going to initialize a variable that stores our tournament scores:

tournament_results = None

Now that we’ve initialized this variable, we can move on to the next part of our program. We call our tournament_results() function to get the tournament data. We then use a for loop to print each value to the console:

tournament_results = tournament_results()

for t in tournament_results:
	print(t)

Our for loop prints each line from our file to the console. Let’s run our code and see what happens:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
	tournament_results = tournament_results()
TypeError: 'NoneType' object is not callable

Our code returns an error message.

The Solution

In our code, we have declared two values with the name “tournament_results”: a function and a variable. We first declare our function and then we declare our variable.

When we declare the “tournament_results” variable, we override the function. This means that whenever we reference “tournament_results”, our program will refer to the variable.

This causes a problem when we try to call our function:

tournament_results = tournament_results()

To solve this error, we should rename the variable “tournament_results” to something else:

final_results = None

final_results = tournament_results()

for f in final_results:
	print(f)

We have renamed the “tournament_results” variable to “final_results”. Let’s see whether this solves the error we experienced:

1: Greg Daniels

2: Lucy Scott

3: Hardy Graham

4: Jenny Carlton

5: Hunter Patterson

Our code successfully prints out all of the text in our file. This is because we’re no longer overriding the “tournament_results” with the value None. 

Conclusion

“TypeError: ‘nonetype’ object is not callable” occurs when you try to call a None value as if it were a function.

To solve it, make sure that you do not override the names of any functions with a None value. Now you have the knowledge you need to fix this error like an expert!

Никогда ботов не писал, но попробую направить:

bot.register_next_step_handler(message, IPMO(message, sumresid))

Вот тут, насколько я понял из документации, вторым аргументом идет callback. Судя по всему, это должен быть указатель на функцию, которая будет запущена, когда придет сообщение. Если вы указываете функцию так, как указали, вы передаете туда возвращаемое значение, а в вашем случае оно будет None, поскольку она ничего не возвращает, соответственно бот будет пытаться запустить None и вы получите ту ошибку, которую получили.

Если загляните вот сюда (ссылка на Github бота), то увидите,

# Handle '/start' and '/help'
@bot.message_handler(commands=['help', 'start'])
def send_welcome(message):
    msg = bot.reply_to(message, """
Hi there, I am Example bot.
What's your name?
""")
    bot.register_next_step_handler(msg, process_name_step)


def process_name_step(message):
    try:
        chat_id = message.chat.id
        name = message.text
        user = User(name)
        user_dict[chat_id] = user
        msg = bot.reply_to(message, 'How old are you?')
        bot.register_next_step_handler(msg, process_age_step)
    except Exception as e:
        bot.reply_to(message, 'oooops')

Тут, во-первых, устанавливается callback строчкой

bot.register_next_step_handler(msg, process_name_step)

а во-вторых сама функция process_name_step принимает в качестве аргумента message, то есть сообщение, которое было прислано боту, а дальше из него уже берется вся информация.

Короче, скорее всего, вам нужно в функции func0, как только поняли, что ID больше одного, отправлять пользователю сообщения с информацией о найденных ID и ждать ответа. Когда ответ придет, сработает callback IMP0 с аргументом message, из которого станет понятно, что именно хочет пользователь, а дальше ваша стандартная обработка ответа.

Ну, и наверное, еще стоит сказать, что лучше было бы, конечно, не спамить кучу сообщений пользователю на каждый ID, а сформировать одно сообщение со всеми найденными ID и отправить пользователю, а дальше уже ждать ответа именно на него, поскольку аргумент message, который идет первым в bot.register_next_step_handler — это, судя по докам, то сообщение, на которое ожидается ответ.

“TypeError: ‘NoneType’ object is not callable” is a common python error that shows up in many ways. What is the cause of it and how to solve it? Let’s follow our article, and we will help you.

What is the cause of this error?

When you attempt to call an object with a None value, such as a function, you will get the TypeError: “NoneType” object is not callable error message. Function calls only have responses from functions.

Example code 1: Attribute and Method have the same name

class Student:
    def __init__(obj):
        obj.fullname = None

    def fullname(obj):
        return obj.fullname # Same name with the method
		
def printMsg():
    print('Welcome to LearnShareIT')
    
def msgStudent(name, function):
    print("Hi", name)
    function() 
	
exStudent = Student()
exStudent.fullname() # TypeError: 'NoneType' object is not callable

Error Message

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-65eab4cbbd19> in <module>
     14 
     15 exStudent = Student()
---> 16 exStudent.fullname()

TypeError: 'NoneType' object is not callable

Example code 2: Misunderstand when calling a function

class Student:
    def __init__(obj):
        obj.fullname = None

    def getFullName(obj):
        return obj.fullname
		
def printMsg():
    print('Welcome to LearnShareIT')
    
def msgStudent(name, function):
    print("Hi", name)
    function() # Calling None object as a function 
	
exStudent = Student()
exStudent.fullname = "Robert Collier"

msgStudent(exStudent.getFullName(), printMsg()) # TypeError: 'NoneType' object is not callable

Error Message

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-618076368e04> in <module>
     16 exStudent.fullname = "Robert Collier"
     17 
---> 18 msgStudent(exStudent.getFullName(), printMsg())
<ipython-input-16-618076368e04> in msgStudent(name, function)
     11 def msgStudent(name, function):
     12     print("Hi",name)
---> 13     function() # Calling None object as a function
     14 
     15 exStudent = Student()

TypeError: 'NoneType' object is not callable

To solve this error, let’s follow two solutions we suggest below:

1) Change the name of method in class

The reason of this error is that when you name the function as the name of a attribute, the attribute will be the first priority to access. As a result, you call the attribute as a function, which cause the Error as the example.

You can change the method name: fullname(obj) to getFullName(obj) as shown the code in the below example to fix the error.

Code sample

class Student:
    def __init__(obj):
        obj.fullname = None

    def getFullName(obj):
        return obj.fullname
		
exStudent = Student()
exStudent.fullname = "Robert Collier"
print(exStudent.getFullName())

Output

'Robert Collier'

2) Remove the parentheses ‘()’

When you pass a non-returning function as a parameter of another function, it is a common mistake to add the parenthesis after the function’s name. It means you call the result of the function as a function accidentally.

Remove the parentheses ‘()’ in the msgStudent(exStudent.getFullName(), printMsg()) statement. The alternative statement would be msgStudent(exStudent.getFullName(), printMsg). When you do that, your error will be fixed.

Code sample

class Student:
    def __init__(obj):
        obj.fullname = None

    def getFullName(obj):
        return obj.fullname
		
def printMsg():
    print('Welcome to LearnShareIT')
    
def msgStudent(name, function):
    print("Hi", name)
    function() # Calling None object as a function 
	
exStudent = Student()
exStudent.fullname = "Robert Collier"

msgStudent(exStudent.getFullName(), printMsg) # Remove ... ()

Output:

Hi Robert Collier
Welcome to LearnShareIT

Summary

In conclusion, “TypeError: ‘nonetype’ object is not callable” occurs when you call a None object as a function. The only way to solve the problem is understanding which parameter is an object and which parameter is a function.

Maybe you are interested:

  • TypeError: ‘NoneType’ object is not iterable in Python
  • TypeError: ‘set’ object is not subscriptable in Python
  • TypeError: ‘str’ object does not support item assignment
  • TypeError: a bytes-like object is required, not ‘str’ in python

My name is Robert Collier. I graduated in IT at HUST university. My interest is learning programming languages; my strengths are Python, C, C++, and Machine Learning/Deep Learning/NLP. I will share all the knowledge I have through my articles. Hope you like them.

Name of the university: HUST
Major: IT
Programming Languages: Python, C, C++, Machine Learning/Deep Learning/NLP

@ishihiroki

My environment

python 3.5.2 anaconda (use pyenv)
keras 2.3.0
tensorflow 1.4.1
theano 1.0.1
cntk 2.3

When backend is tensorflow, TypeError occurs just before learning is finished.

TypeError: ‘NoneType’ object is not callable

Is there a solution?

@ishihiroki

I’m sorry…

keras version is 2.1.3

@pavithrasv

Can you please share a standalone code snippet that can help reproduce the problem?

@chethh

Same problem happens using github/keras/examples/neural_doodle.py.

@chethh

Using latest nvidia, cuda 9.0, tensorflow 1.5, keras installed by current pip3.

@AlexanderKUA

The same issue with Ubuntu native Python3(v3.5.2), Keras(v2.1.5) and Tensorflow(v1.6.0).
Traceback is below:

Exception ignored in: <bound method BaseSession.__del__ of <tensorflow.python.client.session.Session object at 0x7f8a8c2b1f98>>
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 712, in __del__
TypeError: 'NoneType' object is not callable

@hfawaz

@noirmist

I had the same issue. But I tried it again, and it is working fine. It’s weird.

@alexlao

I’ve been getting this issue as well. It only happens sometimes. It’s unfortunate for it to happen after a long training session, as this prevents me from being able to save my models.

@YunheFeng

the same issue on tensorflow:1.7.1-devel-gup-py3 docker tags. Sometimes it works, while sometimes the issue occurs.

@xiaohk

@tgamauf

Same here.

Python 3.5.2
Keras 2.1.5
Tensorflow 1.7

@AsimSaif001

same issue
python 3.5
keras 2.1

@nguyenvulong

same here
python 3.5.2
tensorflow 1.10.1 (with built-in keras)
pip 18.0

@kk2491

As a workaround you can fix the error by writing the below 2 lines of code at the end of training code.

@morpheusthewhite

Same here
python 3.5
tensorflow 1.10
keras 2.2.4

@clappis

I had the same issue. In my case, delete the __pycache__ was a workaround.
rm -rf /usr/lib/{PYTHON_VERSION}/__pycache__/

@supratik-bhattacharya-2020

Same here
python 3.6.9
tensorflow 1.9

@anoopkdcs

Try with (must enable the GPU)
tf.version == 2.4.0
keras.version == 2.4.3
!python —version == Python 3.6.9
print(tf.config.list_physical_devices(‘GPU’)) == [PhysicalDevice(name=’/physical_device:GPU:0′, device_type=’GPU’)]

for me also the same error occurs when I run without enabling the GPU.
but after enabling GPU with the same tf, keras, and python 3.6. It works fine.

@100rab-S

I also faced the same issue. In my case I had a multi output model which was creating the problem. In compile method I had two different metrics for each output layer. But as soon as I replaced the metric with a single metric, the error was gone. Sometimes the error might be from something that doesn’t seem to be obvious as can be seen in my case.

@Armanasq

Same problem here

tf.version == 2.9.1
keras.version == 2.9.0
python —version == Python 3.8

Понравилась статья? Поделить с друзьями:

Читайте также:

  • None local0 info bmminer null 0 invalid nonce hw error
  • Nonce error please reload перевод
  • Non unicode windows 10 как изменить
  • Non system disk press any key как исправить
  • Non system disk or disk error что это

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии