Rectangle 27 354

socket is a module, containing the class socket.

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

Notice that the error here is pretty easy to understand: if module object is not callable, you are probably calling a module object! What's a module object? It's the type of thing you get when you import a module.

But even if you don't understand that (which is fine, it's often confusing that classes, modules, functions etc are all just objects like everything else), there's a pretty easy way to start debugging:

  • "Hmm, module object is not callable. That sounds like I'm trying to call something that you can't call. I wonder what I'm trying to call?"
  • "Oh, I'm calling socket. That should be callable! I wonder if the variable socket is what I think it is?`
print socket

I currently am imporitng socket like this: from socket import *

I also changed it to from socket import socket and I'm still getting the same error.

reload(module)
socket.socket
import write_to_file
write_to_file.py
writeToTextFile
write_to_file.writeToTextFile

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.

python - TypeError: 'module' object is not callable - Stack Overflow

python sockets
Rectangle 27 14

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.

import socket
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've imported socket as: from socket import * I can change it, but it'll take a while, so I'm reluctant to.

@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.

@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.

okay. Thanks for the tip. I've just gotten in the habit from a lot of tutorials.

python - TypeError: 'module' object is not callable - Stack Overflow

python sockets
Rectangle 27 22

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

python - TypeError: 'module' object is not callable - Stack Overflow

python sockets
Rectangle 27 2

When you do import Tkinter as tk, tk refers to a module. This is no different than if you did import Tkinter, where Tkinter refers to a module. Any previous definition of tk is lost.

Later, when you do root = tk(), you are trying to call the module named tk. This is why you are getting the error TypeError: 'module' object is not callable -- you are calling the tkinter module (because of the ()), which you can't do.

The mistake you are making is that the tkinter module defines a class named Tk, and it is this class that you want to call/instantiate. Change your code to do this:

import tkinter as tk
root = tk.Tk()

Also, you shouldn't mix two imports of the same library -- either do import tkinter as tk (recommended) or from tkinter import * but don't do both.

@SkiloSkilo: if you get that error, my guess is that you named your program "tkinter.py" or you have another file named "tkinter.py" that python is loading. Try doing the import, then run the following command to see what is getting loaded: print(tk.__file__)

@SkiloSkilo: rename that file to something else. Your script is importing that instead of the real tkinter module.

python tkinter module object is not callable - Stack Overflow

python-3.x tkinter
Rectangle 27 55

__init__.py
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

python - TypeError: 'module' object is not callable - Stack Overflow

python sockets
Rectangle 27 7

Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object (the same as the module argument).

python - reload (update) a module file in the interpreter - Stack Over...

python module
Rectangle 27 27

Assume that the content of YourClass.py is:

Class YourClass:
......
from YourClassParentDir import YourClass  # means YourClass.py

TypeError: 'module' object is not callable

from YourClassParentDir.YourClass import YourClass   # means Class YourClass

python - TypeError: 'module' object is not callable - Stack Overflow

python sockets
Rectangle 27 60

I have also seen this error when inadvertently naming a module with the same name as one of the standard Python modules. E.g. I had a module called commands which is also a Python library module. This proved to be difficult to track down as it worked correctly on my local development environment but failed with the specified error when running on Google App Engine.

I used abc.py to write a test to demonstrate the import behavior in python, that bites me a lot...

I suspected this and deleted the .py module but forgot to delete the .pyc which was still causing the error.

I created a math module , which is already standard module.

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror
Rectangle 27 60

I have also seen this error when inadvertently naming a module with the same name as one of the standard Python modules. E.g. I had a module called commands which is also a Python library module. This proved to be difficult to track down as it worked correctly on my local development environment but failed with the specified error when running on Google App Engine.

I used abc.py to write a test to demonstrate the import behavior in python, that bites me a lot...

I suspected this and deleted the .py module but forgot to delete the .pyc which was still causing the error.

I created a math module , which is already standard module.

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror
Rectangle 27 11

Load and initialize a module implemented as a Python source file and return its module object. If the module was already initialized, it will be initialized again. The name argument is used to create or access a module object.

Since your second module has the same name as the first module, it won't replace the first one, but will be merged into the first one.

The source code gives us the same answer.imp is a built-in module, defined in import.c. Let's look at at the definition of load_source

static PyObject *
load_source_module(char *name, char *pathname, FILE *fp)
{
    ......
    m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
    Py_DECREF(co);

    return m;
}
PyImport_ExecCodeModuleEx
PyObject *
PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
{
    PyObject *modules = PyImport_GetModuleDict();
    PyObject *m, *d, *v;

    m = PyImport_AddModule(name);
    ......
    d = PyModule_GetDict(m);
    ......
    v = PyEval_EvalCode((PyCodeObject *)co, d, d);
    ......
}

Now, we just need to focus on PyImport_AddModule. Python uses it to obtain a module object. Your parsed source file will be put into this module object.

PyObject *
PyImport_AddModule(const char *name)
{
    PyObject *modules = PyImport_GetModuleDict();
    PyObject *m;

    if ((m = PyDict_GetItemString(modules, name)) != NULL &&
        PyModule_Check(m))
        return m;
    m = PyModule_New(name);
    if (m == NULL)
        return NULL;
    if (PyDict_SetItemString(modules, name, m) != 0) {
        Py_DECREF(m);
        return NULL;
    }
    Py_DECREF(m); /* Yes, it still exists, in modules! */

    return m;
}

Finally, we find the answer. Given a name, if some module already has this name, namely, name in sys.modules, Python won't create a new module, but will reuse that module.

Thank you very much for looking all the way into import.c. I wonder what's the good use case of this. The document could be more explicit about the merger. Other functions in the same module such as load_module and reload has a much better documentation.

Is there a way that the modules are not merged but replaced?

del sys.modules['name of the module']

python - loading modules by imp.load_source with same name resulting m...

python
Rectangle 27 31

The problem is the circular dependency between the modules. a imports b and b imports a. But one of them needs to be loaded first - in this case python ends up initializing module a before b and b.hi() doesn't exist yet when you try to access it in a.

Thank you! It is what I guessed. But I cannot find some documents mention it. If I do need two modules import some attributes from each other, what should I do?

@Stephen Hsu: Breaking circular dependencies is easy. It's already been asked on SO several times. stackoverflow.com/search?q=%5Bpython%5D+circular+dependency

@S.Lott: Thank you. I just know that it is a circular dependencies problem.

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror
Rectangle 27 5

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

Interesting- I don't know if the OP will see this but it's worth a try!

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: python-notes.curiousefficiency.org/en/latest/python_concepts/

python - TypeError: 'module' object is not callable - Stack Overflow

python sockets
Rectangle 27 30

The problem is the circular dependency between the modules. a imports b and b imports a. But one of them needs to be loaded first - in this case python ends up initializing module a before b and b.hi() doesn't exist yet when you try to access it in a.

Thank you! It is what I guessed. But I cannot find some documents mention it. If I do need two modules import some attributes from each other, what should I do?

@Stephen Hsu: Breaking circular dependencies is easy. It's already been asked on SO several times. stackoverflow.com/search?q=%5Bpython%5D+circular+dependency

@S.Lott: Thank you. I just know that it is a circular dependencies problem.

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror
Rectangle 27 32

Part of it is the way the module system works in Python. You can get a sort of "singleton" for free, just by importing it from a module. Define an actual instance of an object in a module, and then any client code can import it and actually get a working, fully constructed / populated object.

This is in contrast to Java, where you don't import actual instances of objects. This means you are always having to instantiate them yourself, (or use some sort of IoC/DI style approach). You can mitigate the hassle of having to instantiate everything yourself by having static factory methods (or actual factory classes), but then you still incur the resource overhead of actually creating new ones each time.

That makes sense. If I want to change an implementation in Python, I simply import from a different location using the same name. But now I am thinking if it's also possible the other way round by defining a MyClassInstances class to each MyClass in Java, which contains only static, fully initialized instances. That would be wired :D

And another idea: Providing a way of changing such imports in python would it make it possible to replace implementations easily without touching all the python files. Instead of from framework.auth.user import User it might be better to write User = lookup('UserImplentation', 'framework.auth.user.User') (the 2nd parameter might be a default value) inside the framework. Then users of the framework would be able to replace/specialize the User implementation without touching the framework.

@tux21b Using defaults to keep the code clean and at the same time providing the opportunity to supply (inject) any semantically correct dependency seems to be the pythonic (or simpler, more natural) way, in my opinion too.

Oversimplifying, answer, in real life, you rarely need just "a singleton", you need to control scope (you might need a thread local singleton, or a session singleton, and so on), this makes me think that the kind of problems solved in Python are not the kind of real world problems actually solved in an enterprise setting

Actually DI is about being able to test and decouple dependencies of code. Also the import feature is similar to static imports in Java, which let me import a single instance of an object.

design patterns - Why is IoC / DI not common in Python? - Stack Overfl...

python design-patterns dependency-injection inversion-of-control architecture
Rectangle 27 4

When you do from module import * everything from that module is fetched into the current namespace and at the end the reference to module is removed. But, due to module caching the module object can still be accessed from sys.modules, so that in case you do some more import later one than it doesn't have to fetch the module again.

import sys
from foo import *
print A, B        #prints 1, 2
A, B = 100, 200
mod = reload(sys.modules['foo'])#use imp.reload for Python 3  
vars().update(mod.__dict__)     #update the global namespace
print A, B        #prints 1, 2
import *

Note that in general the practice of importing * from a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions.

Yes. I use it for interactive session only. I'm a C++ guy, I'm aware of the danger of importing everything from namespace. Thanks!

python - how to reload after "from import *"? - Stack Overflo...

python module python-import
Rectangle 27 41

For accessing the elements of a list you need to use the square brackets ([]) and not the parenthesis (()).

print  wordlists(len(words))
print worldlists[len(words)]
(wordlists(len(words))).append(words)
worldlists[len(words)].append(words)

Canonizing the answer, Hence I made a small edit. Do rollback if you feel to do so. Thanks.

python - TypeError: 'list' object is not callable while trying to acce...

python callable
Rectangle 27 2

As far as I know, there is no way to import a value from a module and have it readable and writable by the importing scope. When you just import foo in Python, it creates a module object named foo. Getting and setting attributes on a module object will change them in the module's scope. But when you from foo import something, foo is imported and a module object is created, but is not returned. Instead, Python copies the values you specified out of foo and puts them in the local scope. If what you are importing is an immutable type like int or str, then changing it and having the changes reflect in the foo module is impossible. It's similar to this:

>>> class N(object):
...   def __init__(self, value):
...     self.value = value
>>> n = N(3)
>>> value = n.value
>>> print value, n.value
3 3
>>> value = 4
>>> print value, n.value
4 3

Excepting crude hacks, if you really want to be able to modify the module's variable, you will need to import the module itself and modify the variable on the module. But generally, having to do this is indicative of bad design. If you are the writer of the foo module in question, you may want to look at some other, more Pythonic ways to solve your problem.

python - cross module variable - Stack Overflow

python import module
Rectangle 27 5

imp.load_compiled returns the compiled module object, it is different to the import statement which also binds the module to a name

import imp
my_module = imp.load_compiled("my_module", "full_path_to_my_module/my_module.pyc")

Then you can do something like:

my_module.yayfunctions('a')
$ cat /tmp/my_module.py
def yayfunctions(a):
    print a
$ python -m compileall /tmp/my_module.py
$ ls /tmp/my_module.py*
my_module.py   my_module.pyc
$ python
>>> import imp
>>> my_module = imp.load_compiled("my_module", "/tmp/my_module.pyc")
>>> my_module.yayfunctions('a')
a
ImportError: No module named another_module
my_module.pyc
another_module.py

In that case, as others have suggested, it's simpler to just add the directory containing my_module to sys.path and use the regular import mechanism, specifically __import__

Here's a function which should do what you want:

import os


def load_path(filepath):
    """Given a path like /path/to/my_module.pyc (or .py) imports the
    module and returns it
    """

    path, fname = os.path.split(filepath)
    modulename, _ = os.path.splitext(fname)

    if path not in sys.path:    
        sys.path.insert(0, path)

    return __import__(modulename)


if __name__ == '__main__':
    # Example usage
    my_module = load_path('/tmp/my_module.py')
    my_module.yayfunctions('test')

thats exactly what I want to do, but I get an import error

@AntiZamba What does the ImportError message say?

Thanks that what I needed. But that leads to another Problem: my_module.pyc doesn't have the if __name__ == '__main__' check and upon importing it is beeing executed (but it would need params)

python - trying to import a *.pyc as a module - Stack Overflow

python import compiled pyc
Rectangle 27 4

I experienced this error because the module was not actually imported. The code looked like this:

import a.b, a.c

# ...

something(a.b)
something(a.c)
something(a.d)  # My addition, which failed.

The last line resulted in an AttributeError. The cause was that I had failed to notice that the submodules of a (a.b and a.c) were explicitly imported, and assumed that the import statement actually imported a.

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror
Rectangle 27 4

I experienced this error because the module was not actually imported. The code looked like this:

import a.b, a.c

# ...

something(a.b)
something(a.c)
something(a.d)  # My addition, which failed.

The last line resulted in an AttributeError. The cause was that I had failed to notice that the submodules of a (a.b and a.c) were explicitly imported, and assumed that the import statement actually imported a.

python - AttributeError: 'module' object has no attribute - Stack Over...

python attributeerror