794
File "C:\Users\Administrator\Documents\Mibot\oops\blinkserv.py", line 82, in __init__
    self.serv = socket(AF_INET,SOCK_STREAM)
TypeError: 'module' object is not callable

Why am I getting this error? I'm confused.

How can I solve this error?

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
user551717
  • 8,217
  • 5
  • 18
  • 9
  • 23
    I once got this error because I had both a (global) variable and a function with the same name. – remustata Jun 13 '17 at 12:35
  • 2
    I got this error with file name pointed to random.py in the same folder where I had a previously worked ipynb file. I changed the name of the file to random_function.py and relaunched the jupyter notebook. The error disappeared. To test if the name random.py was the problem, I changed the file random_function.py back to random.py. The problem came back. Dont name your file after name of a python library. – seakyourpeak Jan 02 '22 at 16:59

17 Answers17

799

socket is a module, containing the class socket.

You need to do socket.socket(...) or from socket import socket:

>>> import socket
>>> socket
<module 'socket' from 'C:\Python27\lib\socket.pyc'>
>>> socket.socket
<class 'socket._socketobject'>
>>>
>>> from socket import socket
>>> socket
<class 'socket._socketobject'>

This is what the error message means:
It says module object is not callable, because your code is calling a module object. A module object is the type of thing you get when you import a module. What you were trying to do is to call a class object within the module object that happens to have the same name as the module that contains it.

Here is a way to logically break down this sort of error:

  • "module object is not callable. Python is telling me my code trying to call something that cannot be called. What is my code trying to call?"
  • "The code is trying to call on socket. That should be callable! Is the variable socket is what I think it is?`
  • I should print out what socket is and check print(socket)
mtraceur
  • 3,254
  • 24
  • 33
Katriel
  • 120,462
  • 19
  • 136
  • 170
  • I currently am imporitng socket like this: from socket import * – user551717 Dec 26 '10 at 16:06
  • 1
    I also changed it to from socket import socket and I'm still getting the same error. – user551717 Dec 26 '10 at 16:07
  • @user: if you do `print socket` you'll see that the name `socket` is a module. It has to have been bound to that module _somewhere_! Read through your code carefully and I'm sure you'll see an `import socket` or some such where you don't expect it. – Katriel Dec 26 '10 at 16:08
  • 4
    Ohh I get it. The `socket.socket` was a little confusing. I simply did `import write_to_file` and then, since the method I was using inside of `write_to_file.py` is named `writeToTextFile` I simply rand `write_to_file.writeToTextFile` – maudulus Jul 30 '14 at 21:26
  • 16
    It's worth noting that this wasn't obvious to at least 133 people who took time to up vote (myself included) who didn't understand this. Now, it's obvious, and next time I reach in my toolbox, I will find this tool when a module is reported as "not callable". Getting started with a new language is the toughest part. – jamesmortensen Sep 27 '14 at 21:04
  • I am coding in Python for 1 day and i wanted to find a method to call classes dinamicaly .... no person said what globals()[] gives you. It doesn't give the class it gives the module ... which is the import file – Lucian Tarna Mar 20 '16 at 14:54
  • 6
    @maudulus I don't find Python very user-friendly in these respects. – Snowcrash Aug 06 '20 at 11:19
  • 2
    Why on earth someone would ever want to have a "handle" to the module itself (which is just a source code file), rather than the class defined in it, in the first place? What is the use case for that? – Anton Samsonov Oct 31 '21 at 10:30
  • 1
    @AntonSamsonov For example in order to have a plugin system which requires an object be given with a certain attribute (or several), e. g. "init" as an entry point. In this case, you can pass a class, an object or a module to this plugin system. – glglgl Jul 05 '22 at 11:04
  • 1
    @AntonSamsonov It also enables you to have several classes in one file of a different name. So I can import a class from, say, a `DbHelperClasses` file and only import the `DBConnectionHelper` class within that file. Even though the file may have several other classes that I don't need. – Cheruvim Aug 01 '22 at 15:03
  • "I don't find Python very user-friendly in these respects" What should it do instead? – Karl Knechtel Sep 18 '22 at 08:18
  • @AntonSamsonov for the same reason that one would use, for example, a namespace in C++ or C# code. – Karl Knechtel Sep 18 '22 at 08:19
  • @LucianTarna `globals()['x']` gives you whatever the global name `x` refers to. If that's "the class", it will give you "the class". If that's "the module", it will give you "the module". If that's some random integer or string, you get that instead. – Karl Knechtel Sep 18 '22 at 08:20
327

Assume that the content of YourClass.py is:

class YourClass:
    # ......

If you use:

from YourClassParentDir import YourClass  # means YourClass.py

In this way, you will get TypeError: 'module' object is not callable if you then tried to call YourClass().

But, if you use:

from YourClassParentDir.YourClass import YourClass   # means Class YourClass

or use YourClass.YourClass(), it works.

Bowen Xu
  • 3,836
  • 1
  • 23
  • 25
133

Add to the main __init__.py in YourClassParentDir, e.g.:

from .YourClass import YourClass

Then, you will have an instance of your class ready when you import it into another script:

from YourClassParentDir import YourClass
Robert
  • 1,357
  • 15
  • 26
Jose Alban
  • 7,286
  • 2
  • 34
  • 19
55

Short answer: You are calling a file/directory as a function instead of real function

Read on:

This kind of error happens when you import module thinking it as function and call it. So in python module is a .py file. Packages(directories) can also be considered as modules. Let's say I have a create.py file. In that file I have a function like this:

#inside create.py
def create():
  pass

Now, in another code file if I do like this:

#inside main.py file
import create
create() #here create refers to create.py , so create.create() would work here

It gives this error as am calling the create.py file as a function. so I gotta do this:

from create import create
create() #now it works.
Asclepius
  • 57,944
  • 17
  • 167
  • 143
Deekshith Anand
  • 2,175
  • 1
  • 21
  • 24
37

Here is another gotcha, that took me awhile to see even after reading these posts. I was setting up a script to call my python bin scripts. I was getting the module not callable too.

My zig was that I was doing the following:

from mypackage.bin import myscript
...
myscript(...)

when my zag needed to do the following:

from mypackage.bin.myscript import myscript
...
myscript(...)

In summary, double check your package and module nesting.

What I am trying to do is have a scripts directory that does not have the *.py extension, and still have the 'bin' modules to be in mypackage/bin and these have my *.py extension. I am new to packaging, and trying to follow the standards as I am interpreting them. So, I have at the setup root:

setup.py
scripts/
      script1
mypackage/
   bin/
      script1.py
   subpackage1/
   subpackage_etc/

If this is not compliant with standard, please let me know.

zerocog
  • 1,703
  • 21
  • 32
24

It seems like what you've done is imported the socket module as import socket. Therefore socket is the module. You either need to change that line to self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM), as well as every other use of the socket module, or change the import statement to from socket import socket.

Or you've got an import socket after your from socket import *:

>>> from socket import *
>>> serv = socket(AF_INET,SOCK_STREAM)
>>> import socket
>>> serv = socket(AF_INET,SOCK_STREAM)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'module' object is not callable
moinudin
  • 134,091
  • 45
  • 190
  • 216
  • I've imported socket as: from socket import * I can change it, but it'll take a while, so I'm reluctant to. – user551717 Dec 26 '10 at 16:00
  • @user You've probably later somewhere got an `import socket`, which will import the module `socket` overriding the class `socket`. See code snippet in edit. – moinudin Dec 26 '10 at 16:02
  • 3
    @user: you should change it. The reason `from <...> import *` imports are __bad, bad, bad__ is more or less this: normally you know exactly what's in the global namespace, because it's exactly what you've put there. But when you `import *`, you fill that namespace with all sorts of stuff that other modules define. In this case, it's unclear where the name `socket` came from -- is it the module or something defined in that module? If you _always_ use `import socket` or `from socket import socket`, you will never have this problem, since you can see exactly what names are in use. – Katriel Dec 26 '10 at 16:06
8

I know this thread is a year old, but the real problem is in your working directory.

I believe that the working directory is C:\Users\Administrator\Documents\Mibot\oops\. Please check for the file named socket.py in this directory. Once you find it, rename or move it. When you import socket, socket.py from the current directory is used instead of the socket.py from Python's directory. Hope this helped. :)

Note: Never use the file names from Python's directory to save your program's file name; it will conflict with your program(s).

fragilewindows
  • 1,394
  • 1
  • 15
  • 26
blackwind
  • 182
  • 1
  • 10
  • 1
    This is definitely worth noting. I was just trying a quick check with sockets so I simply named the file `socket.py`. Well, that was causing this exact same error message. This page put me on the right track: http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html – Czechnology May 26 '16 at 22:04
1

When configuring an console_scripts entrypoint in setup.py I found this issue existed when the endpoint was a module or package rather than a function within the module.

Traceback (most recent call last):
   File "/Users/ubuntu/.virtualenvs/virtualenv/bin/mycli", line 11, in <module>
load_entry_point('my-package', 'console_scripts', 'mycli')()
TypeError: 'module' object is not callable

For example

from setuptools import setup
setup (
# ...
    entry_points = {
        'console_scripts': [mycli=package.module.submodule]
    },
# ...
)

Should have been

from setuptools import setup
setup (
# ...
    entry_points = {
        'console_scripts': [mycli=package.module.submodule:main]
    },
# ...
)

So that it would refer to a callable function rather than the module itself. It seems to make no difference if the module has a if __name__ == '__main__': block. This will not make the module callable.

Luke Exton
  • 3,506
  • 2
  • 19
  • 33
1

you are using the name of a module instead of the name of the class use

import socket

and then

socket.socket(...)

its a weird thing with the module, but you can also use something like

import socket as sock

and then use

sock.socket(...)
TKTrch3
  • 29
  • 3
  • That answer was already given and highly upvoted 11 years ago. You can upvote one of the existing similar answer if you want to confirm it. But please, when answering to old question, be sure to bring new information that was not already given in existing answers. – chrslg Nov 29 '22 at 00:12
0

I guess you have overridden the builtin function/variable or something else "module" by setting the global variable "module". just print the module see whats in it.

umairhhhs
  • 400
  • 6
  • 19
0

I faced the same problem. then I tried not using from YourClass import YourClass

I just copied the whole code of YourClass.py and run it on the main code (or current code).it solved the error

0

Here's a possible extra edge case that I stumbled upon and was puzzled by for a while, hope it helps someone:

In some_module/a.py:

def a():
   pass

In some_module/b.py:

from . import a

def b():
   a()

In some_module/__init__.py:

from .b import b
from .a import a

main.py:

from some_module import b

b()

Then because when main.py loads b, it goes via __init__.py which tries to load b.py before a.py. This means when b.py tries to load a it gets the module rather than the function - meaning you'll get the error message module object is not callable

The solution here is to swap the order in some_module/__init__.py:

from .a import a
from .b import b

Or, if this would create a circular dependency, change your file names to not match the functions, and load directly from the files rather than relying on __init__.py

Stuart Moore
  • 681
  • 5
  • 32
0

I got the same error below:

TypeError: 'module' object is not callable

When calling time() to print as shown below:

import time

print(time()) # Here

So to solve the error, I called time.time() as shown below:

import time

print(time.time()) # Here

Or, I imported time from time as shown below:

from time import time # Here

print(time()) 

Also, I got the same error in Django View because I use @transaction as shown below:

# "views.py"

from django.http import HttpResponse
from django.db import transaction
# ↓ Here ↓
@transaction
def test(request):
    return HttpResponse("Test")

So to solve the error, I use @transaction.atomic as shown below:

# "views.py"

from django.http import HttpResponse
from django.db import transaction
# ↓ Here ↓
@transaction.atomic
def test(request):
    return HttpResponse("Test")
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
0

I had this error when I was trying to use optuna (a library for hyperparameter tuning) with LightGBM. After an hour struggle I realized that I was importing class directly and that was creating an issue.

import lightgbm as lgb

def LGB_Objective(trial):
        parameters = {
            'objective_type': 'regression',
            'max_depth': trial.suggest_int('max_depth', 10, 60),
            'boosting': trial.suggest_categorical('boosting', ['gbdt', 'rf', 'dart']),
            'data_sample_strategy': 'bagging',
            'num_iterations': trial.suggest_int('num_iterations', 50, 250),
            'learning_rate': trial.suggest_float('learning_rate', 0.01, 1.0),
            'reg_alpha': trial.suggest_float('reg_alpha', 0.01, 1.0), 
            'reg_lambda': trial.suggest_float('reg_lambda', 0.01, 1.0)
            }
        
        '''.....LightGBM model....''' 
        model_lgb = lgb(**parameters)
        model_lgb.fit(x_train, y_train)
        y_pred = model_lgb.predict(x_test)
        return mse(y_test, y_pred, squared=True)

study_lgb = optuna.create_study(direction='minimize', study_name='lgb_regression') 
study_lgb.optimize(LGB_Objective, n_trials=200)

Here, the line model_lgb = lgb(**parameters) was trying to call the cLass itself. When I digged into the __init__.py file in site_packages folder of LGB installation as below, I identified the module which was fit to me (I was working on regression problem). I therefore imported LGBMRegressor and replaced lgb in my code with LGBMRegressor and it started working.

enter image description here

You can check in your code if you are importing the entire class/directory (by mistake) or the target module within the class.

from lightgbm import LGBMRegressor

def LGB_Objective(trial):
        parameters = {
            'objective_type': 'regression',
            'max_depth': trial.suggest_int('max_depth', 10, 60),
            'boosting': trial.suggest_categorical('boosting', ['gbdt', 'rf', 'dart']),
            'data_sample_strategy': 'bagging',
            'num_iterations': trial.suggest_int('num_iterations', 50, 250),
            'learning_rate': trial.suggest_float('learning_rate', 0.01, 1.0),
            'reg_alpha': trial.suggest_float('reg_alpha', 0.01, 1.0), 
            'reg_lambda': trial.suggest_float('reg_lambda', 0.01, 1.0)
            }
        
        '''.....LightGBM model....''' 
        model_lgb = LGBMRegressor(**parameters) #here I've changed lgb to LGBMRegressor
        model_lgb.fit(x_train, y_train)
        y_pred = model_lgb.predict(x_test)
        return mse(y_test, y_pred, squared=True)

study_lgb = optuna.create_study(direction='minimize', study_name='lgb_regression') 
study_lgb.optimize(LGB_Objective, n_trials=200)
Bhanu Chander
  • 390
  • 1
  • 6
  • 16
0

in your case try it

    from socket import socket

in addition

    #in a separate file you define a class like:

    class one:
              def __init__(self, name, value):
               self.name = name
               self.value = value
              pass

    #and in other file you define a other class.
    #and you want use defined class inside it.like:
    
    from one import one as clsOne #this model of import a class solve the error
    class two:
              item = clsOne("A", 22)
              print(item.name)
             pass
Ali Seify
  • 41
  • 4
-1

A simple way to solve this problem is export thePYTHONPATH variable enviroment. For example, for Python 2.6 in Debian/GNU Linux:

export PYTHONPATH=/usr/lib/python2.6`

In other operating systems, you would first find the location of this module or the socket.py file.

fragilewindows
  • 1,394
  • 1
  • 15
  • 26
Oscar Ardila
  • 67
  • 1
  • 4
-3

check the import statements since a module is not callable. In Python, everything (including functions, methods, modules, classes etc.) is an object.

Ayesha Siddiqa
  • 345
  • 2
  • 3