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?
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)
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.
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
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.
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.
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
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).
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.
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
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(...)
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.
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
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, 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())
Then, the error was solved:
1671301094.5742612
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.
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)
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.
check the import statements since a module is not callable.
In Python, everything (including functions, methods, modules, classes etc.) is an object.
I'm absolutely frustraded about the fact that I can't start my Python journey. I have a simple service which I use as a training with Python which is new for me.
I've downloaded PyCharm and as long as I had one file, everything was fine.
That I decided to to some structure and suddenly my project stopped working.
I have a structure like:
project/
project/employees
project/employees/__init__.py
project/employees/employees.py
project/server.py
project/venv/
project/venv/(...)
The project is a source root.
And yet I have something like this:
Traceback (most recent call last):
File "C:/Users/user/PycharmProjects/project/server.py", line 5, in <module>
from employees.employees import Employees, EmployeesName
File "C:\Users\user\PycharmProjects\project\employees\employees.py", line 4, in <module>
from server import db_connect
File "C:\Users\user\PycharmProjects\project\server.py", line 5, in <module>
from employees.employees import Employees, EmployeesName
ImportError: cannot import name 'Employees'
I tested this with VS Code and CMD and the same happend.
I would be grateful for any suggestions!
EDIT:
employees.py:
from flask_jsonpify import jsonify
from flask_restful import Resource
from server import db_connect
class Employees(Resource):
(...)
class EmployeesName(Resource):
(...)
The problem here is that you have a circular dependency.
In employees.py you import server.py; and vice versa.
You have to rearrange your .py files in order that not to happen anymore.
recently i have created this topic and did not get the answer.
after that i edited this and added 2 screenshots.
right now i tested another temporary email library and got the same error :((
this library :
pip install python-guerrillamail
code python 2.7:
from guerrillamail import GuerrillaMailSession
session = GuerrillaMailSession()
print session.get_session_state()['email_address']
print session.get_email_list()[0].guid
it seemed i cant never work like this email lib.
updated after remove email.pyc:
Traceback (most recent call last):
File "C:\Users\11\Desktop\untitle.py", line 1, in <module>
from guerrillamail import Guerrillamail
ImportError: cannot import name Guerrillamail
Your module email.py, is shadowing, or hiding, the email package in Python's standard library. This is causing the error: in the traceback you can see that an error is being reported when the statement import email is executed.
Rename your file to something else, for example myemail.py.
I changed the code to " from guerrillamail import * " that is worked. this code seems import all things to program, maybe it causes to be heavy and executing time.
thanks to #snakecharmerb .
New to Python I'm trying to setup a simple OOP-structure of files, folders and classes. Here are the file paths:
C:\Users\Mc_Topaz\Programmering\Python\Terminal\Main.py
C:\Users\Mc_Topaz\Programmering\Python\Terminal\Connections\Connection.py
C:\Users\Mc_Topaz\Programmering\Python\Terminal\Connections\NoConnection.py
Notice Connection.py and NoConnection.py is loacted in sub folder Connections.
Connection.py
class Connection:
def __init__(self):
pass
def ToString(self):
pass
NoConnection.py
from Connection import Connection
class NoConnection(Connection):
def __init__(self):
pass
def ToString(self):
print("No connection")
In the Main.py file I would like to call the ToString() method from each class.
Main.py
from Connections.Connection import Connection
from Connections.NoConnection import NoConnection
connection = Connection()
print(connection.ToString())
noConnection = NoConnection()
print(noConnection.ToString())
When I run the Main.py file I get this error:
C:\Users\Mc_Topaz\Programmering\Python\Terminal>Main.py Traceback
(most recent call last): File
"C:\Users\Mc_Topaz\Programmering\Python\Terminal\Main.py", line 2, in
from Connections.NoConnection import NoConnection
File
"C:\Users\Mc_Topaz\Programmering\Python\Terminal\Connections\NoConnection.py",
line 1, in
from Connection import Connection
ImportError: No module named 'Connection'
It seems that the interpreter cannot import the NoConnection class in my Main.py file due to it cannot import the Connection class from the NoConnection.py file.
I can run Connection.py and NoConnection.py separately with no problems.
I don't understand why the Main.py don't run. I assume is something super simple and I cannot see it due to I'm to green to Python.
For python to recognize a directory is a module, or a collection of python files, that directory must contain a file named __init__.py. That file doesn't need to contain anything code whatsoever, though it can. If you add this file to your Connections directory, the interpreter should be able to import the contained files.
Just to add on to what mobiusklein mentioned: a common practice with __init__.py is to import the objects you use most frequently to avoid redundancy in your imports. In your example your Connections\__init__.py would likely contain:
import Connection
import NoConnection
Then your Main.py could use the following import statements successfully:
from Connections import Connection, NoConnection
I think it's down to relative imports in Python 3.
Change the import line in NoConnection to be explicit...
from Connections.Connection import Connection
and it works in Python3 (it works either way in Python2). Path to Terminal may have to be on you PYTHONPATH environment variable.
"Python 3 has disabled implicit relative imports altogether; imports are now always interpreted as absolute, meaning that in the above example import baz will always import the top-level module. You will have to use the explicit import syntax instead (from . import baz)." from here https://softwareengineering.stackexchange.com/questions/159503/whats-wrong-with-relative-imports-in-python
So when you import Connection from NoConnection it will be looking for it at the Terminal level, not at the Terminal/Connections level.
UPDTAE: Read comments for this post as it contain the solution.
Still don't get this to work. But I have made some changes:
Changed names of classes
> Class Connection = Foo inside Connection.py
> NoConnection = Bar inside NoConnection.py
This is ensure that the interpreter don't get confused if Connection is a module or a class.
Dropped ini.py file
I have dropped the Connections\__init_.py file as this don't seem to be necessary in Python version 3.4.2.
Files still run separately
I can run Connection.py and NoConnection.py separately. So they work.
Main.py
from Connections.NoConnection import Bar
noConnection = Bar()
print(noConnection.ToString())
When running Main.py I get the same error at line 1:
"Cannot find module 'Connection' in NoConnection.py at line 1".
The only logical reason I can see why this error happens is:
The interpreter looks for Connection.py inside my Terminal folder as Python was started from that folder. Even if it's importing the NoConnection.py file from the Connections folder where Connection.py is located.
Is this a bug?
For this problem (stackoverflow.com/questions/4086435/), I tried to make a Python 3 version of the library python-websocket (github.com/mtah/python-websocket/), here is my code: https://gist.github.com/663175.
Blender comes with his own Python 3.1 package, so I added my file directly in its «site-packages» folder. I get this error now:
Traceback (most recent call last):
File "websocket.py", line 6, in
AttributeError: 'module' object has no attribute 'WebSocket'
when running this code in Blender:
import sys, os, asyncore, websocket
def msg_handler(msg):
print(msg)
socket = websocket.WebSocket('ws://localhost:8080/', onmessage=msg_handler)
socket.onopen = lambda: socket.send('Hello world!')
try:
asyncore.loop()
except KeyboardInterrupt:
socket.close()
I found that a __init__.py is needed so I added but it didn't help…
What I am doing wrong here ? Thanks for your help.
It looks like you called your script websocket.py, so the import of websocket finds the script itself, instead of the installed module by that name. Rename the script to something else (and if it created a websocket.pyc file, delete that.)