Can be a duplication - TypeError: the 'module' object is not callable

advertisements

I have been working with Python for about a year now, and I'm starting to write my own modules. I'm trying to make a module that imports a bunch of useful modules at the same time. The module imports fine. When I try to run it, it gives the error

Traceback (most recent call last):
    File "<pyshell#1>", line 1, in <module>
        importuseful()
TypeError: 'module' object not callable

My file name is importuseful.py My code is:

def importuseful():

    import sys

    import os

    import RPi.GPIO as GPIO

    import GPIO as gpio

    import random

    import math

    import time

    import email

    import tty

    import turtle

I run at the IDLE shell:

from Modules import importuseful

importuseful()

Here is where it throws the TypeError

The path it is in is /home/pi/Modules, and that is set as part of $PYTHONPATH.

The only other module I have made is GPIO which is one I am trying to import. I was having the same problem with that one, but that one fixed itself. Anyone have any ideas on what is wrong or how to fix?


As Padraic Cunningham said, you need to call the function inside the module.

from Modules import importuseful

importuseful.importuseful()

However, this isn't going to do what you want, because the modules will only be imported in the function scope. For instance:

>>> def importuseful():
...     import math
...
>>> importuseful()
>>> math
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
>>>

You should just include only the modules you need at the top of every file. No need to import unnecessary modules.

If you really want to do this (which I don't recommend), you could put the imports directly into a module, then import everything from that module.

# usefulimports.py

import functools
import itertools
import math

# script.py

from usefulimports import *