Меню

Series object is not callable ошибка

The TypeError ‘Series’ object is not callable occurs when you try to call a Series object by putting parentheses () after it like a function. Only functions respond to function calls.

You can solve this error by using square brackets to access values in a Series object. For example,

import pandas as pd

vals = {'x': 73 , 'y': 21, 'z': 10}

ser = pd.Series(data=vals)

print(ser['x'])

This tutorial will go through the error in detail and how to solve it with the help of code examples.


Table of contents

  • TypeError: ‘Series’ object is not callable
  • Example #1
    • Solution #1: Use square brackets
    • Solution #2: Use dot notation
  • Example #2: Reassigning a Reserved Name
    • Solution
  • Summary

TypeError: ‘Series’ 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("Learning Python is fun!")

# Call function

simple_function()
Learning Python is fun!

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().

Series objects do not respond to a function call because they are not functions. If you try to call a Series object as if it were a function, you will raise the TypeError: ‘Series’ object is not callable.

We can check if an object is callable by passing it to the built-in callable() method. If the method returns True, then the object is callable. Otherwise, if it returns False the object is not callable. Let’s look at evaluating a Series object with the callable method:

import pandas as pd

vals = {'x': 73 , 'y': 21, 'z': 10}

ser = pd.Series(data=vals)

print(callable(ser))
False

The callable function returns False for the Series object.

Example #1

Let’s look at an example of attempting to call a Series object. First, we will import pandas and then create a Series object from a dictionary containing pizza names as keys and pizza prices as values.

import pandas as pd

pizzas = {'margherita': 10.99 , 'pepperoni': 11.99, 'marinara': 7.99}

ser = pd.Series(data=pizzas)

Next, we will try to access the row with the index ‘marinara‘.

print(ser('marinara'))

Let’s run the code to see what happens:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [17], in <cell line: 7>()
      3 pizzas = {'margherita': 10.99 , 'pepperoni': 11.99, 'marinara': 7.99}
      5 ser = pd.Series(data=pizzas)
----> 7 print(ser('marinara'))

TypeError: 'Series' object is not callable

The error occurs because we tried to access the row with the index ‘marinara‘ using parentheses. Putting parentheses after the Series object is interpreted by Python as a function call.

Solution #1: Use square brackets

To solve this error, we can access the row of the Series object using square brackets. Let’s look at the revised code:

import pandas as pd

pizzas = {'margherita': 10.99 , 'pepperoni': 11.99, 'marinara': 7.99}

ser = pd.Series(data=pizzas)

print(ser['marinara'])

print(type(ser['marinara']))

Let’s run the code to see the result:

7.99
<class 'numpy.float64'>

The above value is a numpy.float64 containing the price of the marinara pizza.

Solution #2: Use dot notation

We can also use the dot notation to access the attributes of the Series object. We can use the dir() method to list the attributes of the object:

Let’s look at the revised code:

import pandas as pd

pizzas = {'margherita': 10.99 , 'pepperoni': 11.99, 'marinara': 7.99}

ser = pd.Series(data=pizzas)

print(ser.marinara])

We used the dot notation to access the marinara row of the Series object. Let’s run the code to get the result:

7.99

Example #2: Reassigning a Reserved Name

The error can also occur if we reassign a reserved name for a built-in function like list() to Series object.

Let’s look at an example:

import pandas as pd

pizzas = {'margherita': 10.99 , 'pepperoni': 11.99, 'marinara': 7.99}

list = pd.Series(data=pizzas)

a_set = {2, 4, 6}

list(a_set)

In the above code, we defined a Series object and then assigned it to the variable name list. We then define a set of integers and try to convert it to a list using the built-in list() method. Let’s run the code to see what happens:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [22], in <cell line: 9>()
      5 list = pd.Series(data=pizzas)
      7 a_set = {2, 4, 6}
----> 9 list(a_set)

TypeError: 'Series' object is not callable

The error occurs because when we assigned the Series object to the variable name, list we overrode the built-in list() method. Then when we try to convert the set to a list, we are instead trying to call the Series object, which is not callable.

Solution

We can solve this error by using variable names not reserved for built-in functions. We can find the names of built-in functions using:

print(dir(__builtins__))

Let’s look at the revised code:

import pandas as pd

pizzas = {'margherita': 10.99 , 'pepperoni': 11.99, 'marinara': 7.99}

ser = pd.Series(data=pizzas)

a_set = {2, 4, 6}

list(a_set)

Note that we will have to create a new session if we are using an interactive Python shell so that the list variable is correctly assigned to the list() method.

Let’s run the code to get the result:

[2, 4, 6]

Summary

Congratulations on reading to the end of this tutorial!

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

  • How to Solve Python TypeError: ‘DataFrame’ object is not callable.
  • How to Solve Python TypeError: ‘datetime.datetime’ object is not callable.
  • How to Solve Python TypeError: ‘range’ object is not callable
  • How to Solve Python TypeError: ‘set’ 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!

When I try to run the following

df['ln_returns'] = np.log(df['Close_mid']/df['Close_mid'](1))

I get the error

'Series' object is not callable 

When checking df.dtypes i get:

0
Close_mid      float64
Close_large    float64
Close_small    float64
dtype: object

And when checking

print(type(df.Close_mid))
<class 'pandas.core.series.Series'>

How do I solve this ambiguity?
I’m trying to calculate the logarithmic change between to periods

asked Jul 22, 2019 at 11:57

MisterButter's user avatar

MisterButterMisterButter

7391 gold badge10 silver badges25 bronze badges

4

The source of this error is that you wrote df['Close_mid'](1).
In this case Pandas acts as follows:

  • gets df['Close_mid'] (a column of your DataFrame),
  • tries to call it, passing a single parameter (1).

If you want to divide each element of this column by its first element, write:

df['Close_mid']/df['Close_mid'].iloc[0]

(note that in a Series the numeration of elements starts just from 0).

If you want to refer to the previous/next element, use shift().

answered Jul 22, 2019 at 12:13

Valdi_Bo's user avatar

Valdi_BoValdi_Bo

29.3k4 gold badges24 silver badges38 bronze badges

1

What you have is a Series of float64 type values. There is no ambiguity.

df['Close_mid'] is a Series and is not callable. Trying to call it like so df['Close_mid'](1) raises the error.
Maybe you can elaborate on what you are trying to do with calling with (1).

answered Jul 22, 2019 at 12:05

Teodor Ivanov's user avatar

1

What are you trying by adding «(1)»?

Try this:

df['ln_returns'] = np.log(df['Close_mid']/df['Close_mid'])

answered Jul 22, 2019 at 12:07

Daniziz's user avatar

1

1 answer to this question.

Try this:

df['ln_returns'] = np.log(df['Close_mid']/df['Close_mid'])

df[‘Close_mid’](1)) doesn’t seem to be doing anything

Hope it helps!!

If you need to know more about Python, It’s recommended to join Python course today.

Thanks!






answered

Jul 22, 2019


by
Greg



Related Questions In Python

  • All categories

  • Apache Kafka
    (84)

  • Apache Spark
    (596)

  • Azure
    (131)

  • Big Data Hadoop
    (1,907)

  • Blockchain
    (1,673)

  • C#
    (141)

  • C++
    (271)

  • Career Counselling
    (1,060)

  • Cloud Computing
    (3,436)

  • Cyber Security & Ethical Hacking
    (147)

  • Data Analytics
    (1,266)

  • Database
    (855)

  • Data Science
    (75)

  • DevOps & Agile
    (3,570)

  • Digital Marketing
    (111)

  • Events & Trending Topics
    (28)

  • IoT (Internet of Things)
    (387)

  • Java
    (1,247)

  • Kotlin
    (8)

  • Linux Administration
    (389)

  • Machine Learning
    (337)

  • MicroStrategy
    (6)

  • PMP
    (423)

  • Power BI
    (516)

  • Python
    (3,188)

  • RPA
    (650)

  • SalesForce
    (92)

  • Selenium
    (1,569)

  • Software Testing
    (56)

  • Tableau
    (608)

  • Talend
    (73)

  • TypeSript
    (124)

  • Web Development
    (3,002)

  • Ask us Anything!
    (66)

  • Others
    (1,838)

  • Mobile Development
    (263)

Subscribe to our Newsletter, and get personalized recommendations.

Already have an account? Sign in.

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!

Jun-23-2018, 11:16 AM
(This post was last modified: Jun-23-2018, 11:17 AM by Jack_Sparrow.)

Hello there
this is my data set

Vote_count vote_average
2000 4,5
500 5
3500 4
3000 3,5
2700 4,5
1500 3,5

I want to count how many people (vote_count) gave which rating in one bar chart (x axis: rating_vote and y axis: vote_count)

this is my code

df_star_trek['vote_average']('vote_count').sum().plot(kind='bar');

I get this error message

TypeError                                 Traceback (most recent call last)
<ipython-input-102-d361146a8034> in <module>()
      1 #what is the vote avarage for Star Wars and Star Treck?
----> 2 df_star_trek['vote_average']('vote_count').sum().plot(kind='bar');

TypeError: 'Series' object is not callable

Why? How can I fix it?

Posts: 333

Threads: 4

Joined: Jun 2018

Reputation:
24

Could you provide how df_star_trek was instantiated?
And you use (‘vote_count’) with a key of this df_star_trek, the () is for callable instances.
Maybe if you change to [‘vote_count’] your code will run ok.

Posts: 36

Threads: 24

Joined: Apr 2018

Reputation:
0

I just filtered my data set to the Film «Star Trek»

df_star_trek = df[df['original_title'].str.contains("Star Trek", na=False)]

I changed the brackets from () to []
Now I have this mistake

NameError: name 'df_star_trek' is not defined

In my opinion, it is defined, isn’t it?

Posts: 333

Threads: 4

Joined: Jun 2018

Reputation:
24

Quote:In my opinion, it is defined, isn’t it?

I don’t think so. For some reason this part of your code is not been executed.

df_star_trek = df[df['original_title'].str.contains("Star Trek", na=False)]

Автор оригинала: Shubham Sayon.

Обзор

Цель: Цель этой статьи – обсудить и исправить TypeError: «Модуль» объект не вызывается в питоне. Мы будем использовать многочисленные иллюстрации и методы для решения проблемы упрощенным образом.

Пример 1. :

# Example of TypeError:'module' object is not callable
import datetime  # importing datetime module


def tell_date():  # Method for displaying today's date
    return datetime()


print(tell_date())

Выход:

Traceback (most recent call last):
  File "D:/PycharmProjects/PythonErrors/rough.py", line 9, in 
    print(tell_date())
  File "D:/PycharmProjects/PythonErrors/rough.py", line 6, in tell_date
    return datetime()
TypeError: 'module' object is not callable

Теперь вышеупомянутый выход приводит нас к нескольким вопросам. Давайте посмотрим на них один за другим.

Типеррор является одним из наиболее распространенных исключений в Python. Вы столкнетесь с Исключение типа «Типерре» В Python всякий раз, когда есть несоответствие в типов объектов в определенной работе. Это обычно происходит, когда программисты используют неверные или неподдерживаемые типы объектов в своей программе.

Пример: Посмотрим, что произойдет, если мы попытаемся объединить ул ...| объект с int объект:

# Concatenation of str and int object
string = 'Nice'
number = 1
print(string + number)

Выход:

Traceback (most recent call last):
  File "D:/PycharmProjects/PythonErrors/rough.py", line 4, in 
    print(string + number)
TypeError: can only concatenate str (not "int") to str

Объяснение:

В приведенном выше примере мы можем ясно видеть, что Исключение типа «Типерре» произошло потому, что мы можем только объединять ул ...| другому ул …| Объект и не к любому другому типу объекта (например, int , float , etc .)

  • « + «Оператор может объединить ул ...| (строки) объекты. Но в случае int (целые числа), он используется для добавления. Если вы хотите насильственно выполнять конкатенацию в приведенном выше примере, вы можете легко сделать это, напечатавшись на
  • int объект к ул …| тип.

📖 Читайте здесь: Как исправить JypeError: Список индексов должен быть целыми числами или ломтиками, а не «STR»?

Итак, от предыдущих иллюстраций у вас есть четкое представление о Типеррор Отказ Но что делает исключение TypeError: «Модуль» объект не вызывается иметь в виду?

🐞 Типеррера: «Модуль» объект не вызывается

Python обычно предоставляет сообщение с поднятыми исключениями. Таким образом, Исключение типа «Типерре» Есть сообщение Объект «Модуль» не является Callable , что означает, что вы пытаетесь вызвать объект модуля вместо класса или объекта функции внутри этого модуля.

Это происходит, если вы попытаетесь вызвать объект, который не вызывается. Callable объект может быть классом или методом, который реализует __вызов__ «Метод. Причина этого может быть (1) Путаница между именем модуля и именем класса/функции внутри этого модуля или (2) неверный класс или вызов функции.

Причина 1 : Давайте посмотрим на примере первой причины, то есть Путаница между именем модуля и именем класса/функции Отказ

  • Пример 2 : Рассмотрим следующий пользовательский модуль – решить .py :
# Defining solve Module to add two numbers
def solve(a, b):
    return a + b

Теперь давайте попробуем импортировать вышеуказанный пользовательский модуль в нашей программе.

import solve

a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
print(solve(a, b))

Выход:

Enter first number: 2
Enter second number: 3
Traceback (most recent call last):
  File "main.py", line 6, in 
    print(solve(a, b))
TypeError: 'module' object is not callable

Объяснение: Здесь пользователь запутался между именем модуля и именем функции, так как они оба являются точно такими же, I.e. ‘ решить ‘.

Причина 2 : Теперь, давайте обсудим еще один пример, который демонстрирует следующую причину, то есть неправильный класс или звонок функции.

Если мы выполним неверный импорт или функциональную операцию вызова, то мы, вероятно, снова станем исключением. Ранее в примере, приведенном в обзоре, мы сделали неверный вызов, позвонив datetime Объект модуля вместо объекта класса, который поднял TypeError: «Модуль» объект не вызывается исключением.

Теперь, когда мы успешно прошли причины, которые приводят к возникновению нашей проблемы, давайте найдем решения для его преодоления.

📚 Как исправить TypeError: «Модуль» объект не вызывается ?

🖊️ Метод 1: Изменение оператора «Импорт»

Для исправления первой проблемы, которая является путаницей между именем модуля и именем класса/функции, позвольте нам пересмотреть Пример 2 Отказ Здесь модульрешить У также есть Метод назван «RELVE» , таким образом создавая путаницу.

Чтобы исправить это, мы можем просто изменить оператор импорта, импортируя конкретную функцию внутри этого модуля или просто импортируя все классы и методы внутри этого модуля.

# importing solve module in Example 2
from solve import solve

a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
print(solve(a, b))

Выход:

Enter first number: 2
Enter second number: 3
5

📝 Примечание:

  • Импорт всех классов и методов рекомендуется только в том случае, если размер импортируемого модуля небольшой, поскольку он может повлиять на временную и космическую сложность программы.
  • Вы также можете использовать псевдоним, используя подходящее имя, если у вас все еще есть путаница.
    • Например: – от решающего импорта решить как соль

🖊️ Метод 2: Использование. (Точка) нотация для доступа к классам/методам

Есть еще одно решение для той же проблемы. Вы можете получить доступ к атрибутам, классам или методам модуля, используя «.» Оператор. Поэтому вы можете использовать то же самое, чтобы исправить нашу проблему.

Давайте попробуем это снова на нашем примере 2.

# importing solve module in Example 2
import solve

a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
print(solve.solve(a, b))

Выход:

Enter first number: 2
Enter second number: 3
5

🖊️ Метод 3: Реализация правильного вызова класса или функции

Теперь давайте обсудим решение второй причине нашей проблемы, то есть, если мы выполним неверный класс или вызов функции. Любая ошибка в реализации вызова может привести к тому, что может вызвать Ошибки в программе. Пример 1 имеет точно такую же проблему неправильного вызова функции, который поднял исключение.

Мы можем легко решить проблему, заменив неверное оператор вызовов с помощью правильного, как показано ниже:

import datetime  # importing datetime module
def tell_date():  # Method for displaying today's date
    return datetime.date.today()
print(tell_date())

Выход:

💰 Бонус

Вышеупомянутое Типеррор происходит из-за многочисленных причин. Давайте обсудим некоторые из этих ситуаций, которые приводят к возникновению аналогичного вида Типеррор Отказ

✨ JypeError ISERROR: объект «Список» не вызывается

Эта ошибка возникает, когда мы пытаемся вызвать объект «списка», а вы используете «()» вместо использования «[]».

Пример:

collection = ['One', 2, 'three']
for i in range(3):
    print(collection(i))  # incorrect notation

Выход:

Traceback (most recent call last):
  File "D:/PycharmProjects/PythonErrors/rough.py", line 3, in 
    print(collection(i))  # incorrect notation
TypeError: 'list' object is not callable

Решение: Чтобы исправить эту проблему, нам нужно использовать правильный процесс доступа к элементам списка I.e, используя «[]» (квадратные скобки). Так просто! 😉.

collection = ['One', 2, 'three']
for i in range(3):
    print(collection[i])  # incorrect notation

Выход:

✨ Типеррера: «INT» Объект не Callable

Это еще одна общая ситуация, когда пользователь призывает int объект и заканчивается с Типеррор Отказ Вы можете столкнуться с этой ошибкой в сценариях, таких как следующее:

Объявление переменной с именем функции, которая вычисляет целочисленные значения

Пример:

# sum variable with sum() method
Amount = [500, 600, 700]
Discount = [100, 200, 300]
sum = 10
if sum(Amount) > 5000:
    print(sum(Amount) - 1000)
else:
    sum = sum(Amount) - sum(Discount)
    print(sum)

Выход:

Traceback (most recent call last):
  File "D:/PycharmProjects/PythonErrors/rough.py", line 5, in 
    if sum(Amount)>5000:
TypeError: 'int' object is not callable

Решение: Чтобы исправить эту проблему, мы можем просто использовать другое имя для переменной вместо сумма Отказ

#sum variable with sum() method
Amount = [500, 600, 700]
Discount = [100, 200, 300]
k = 10
if sum(Amount)>5000:
    print(sum(Amount)-1000)
else:
    k = sum(Amount)-sum(Discount)
    print(k)

Выход:

Вывод

Мы наконец достигли конца этой статьи. Фу! Это было некоторое обсуждение, и я надеюсь, что это помогло вам. Пожалуйста, Подписаться и Оставайтесь настроиться Для более интересных учебных пособий.

Спасибо Anirban Chatterjee Для того, чтобы помочь мне с этой статьей!

  • Вы хотите быстро освоить самые популярные Python IDE?
  • Этот курс приведет вас от новичка к эксперту в Пычарме в ~ 90 минут.
  • Для любого разработчика программного обеспечения имеет решающее значение для освоения IDE хорошо, писать, тестировать и отлаживать высококачественный код с небольшим усилием.

Присоединяйтесь к Pycharm MasterClass Сейчас и мастер Pycharm на завтра!

Я профессиональный Python Blogger и Content Creator. Я опубликовал многочисленные статьи и создал курсы в течение определенного периода времени. В настоящее время я работаю полный рабочий день, и у меня есть опыт в областях, таких как Python, AWS, DevOps и Networking.

Вы можете связаться со мной @:

  • Заработка
  • Linkedin.

Python is well known for the different modules it provides to make our tasks easier. Not just that, we can even make our own modules as well., and in case you don’t know, any Python file with a .py extension can act like a module in Python. 

In this article, we will discuss the error called “typeerror ‘module’ object is not callable” which usually occurs while working with modules in Python. Let us discuss why this error exactly occurs and how to resolve it. 

Fixing the typerror module object is not callable error in Python 

Since Python supports modular programming, we can divide code into different files to make the programs organized and less complex. These files are nothing but modules that contain variables and functions which can either be pre-defined or written by us. Now, in order to use these modules successfully in programs, we must import them carefully. Otherwise, you will run into the “typeerror ‘module’ object is not callable” error. Also, note that this usually happens when you import any kind of module as a function.  Let us understand this with the help of a few examples.

Example 1: Using an in-built module

Look at the example below wherein we are importing the Python time module which further contains the time() function. But when we run the program, we get the typeerror. This happens because we are directly calling the time module and using the time() function without referring to the module which contains it.

Python3

import time

inst = time()

print(inst)

Output

TypeError                                 Traceback (most recent call last)
Input In [1], in <module>
      1 import time
----> 2 inst = time()
      3 print(inst)

TypeError: 'module' object is not callable

From this, we can infer that modules might contain one or multiple functions, and thus, it is important to mention the exact function that we want to use. If we don’t mention the exact function, Python gets confused and ends up giving this error. 

Here is how you should be calling the module to get the correct answer:

Python3

from time import time 

inst = time()

print(inst)

Output

1668661030.3790345

You can also use the dot operator to do the same as shown below-

Python3

import time

inst = time.time()

print(inst)

Output

1668661346.5753343

Example 2: Using a custom module

Previously, we used an in-built module. Now let us make a custom module and try importing it. Let us define a module named Product to multiply two numbers. To do that, write the following code and save the file as Product.py

Python3

def Product(x,y):

  return x*y

Now let us create a program where we have to call the Product module to multiply two numbers. 

Python3

import Product

x = int(input("Enter the cost: "))

y = int(input("Enter the price: "))

print(Product(a,b))

Output

Enter first number: 5
Enter second number: 10
Traceback (most recent call last):
  File "demo.py", line 6, in <module>
    print(Product(a, b))
TypeError: 'module' object is not callable

Why this error occurs this time? 

Well again, Python gets confused because the module as well as the function, both have the same name. When we import the module Product, Python does not know if it has to bring the module or the function. Here is the code to solve this issue:

Python3

from Product import Product

x = int(input("Enter the cost: "))

y = int(input("Enter the price: "))

print(Product(a,b))

Output

Enter the cost: 5
Enter the price: 10
50 

We can also use the dot operator to solve this issue. 

Python3

import Product

x = int(input("Enter the cost: "))

y = int(input("Enter the price: "))

print(Product.Product(a,b))

Output

Enter the cost: 5
Enter the price: 10
50 

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

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

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Serdes count samsung ошибка
  • Secur32 dll ошибка как исправить виндовс 7