TypeError: 'module object is not callable'

  • Thread starter Bruno Desthuilliers
  • Start date
B

Bruno Desthuilliers

(e-mail address removed) a écrit :
(snip)
I have another little question before I finish today:
I am currently struggling to use a global variable in my static
functions. I'll explain further

Within my main.py file I have

class Main(object):
stepStore = StepStore()

@staticmethod
def createDepSteps():
....
stepStore.addStep([bol7, pre5])
.......

@staticmethod
def processSteps():
for step in stepStore.stepList[:]:
......

Main.createDepSteps()
Main.processSteps()
(snip)

Marc and Diez already gave you the good answers on this (basically: get
rid of useless classes, and use plain functions instead of
staticmethods). I'd just add a couple comments:

First point: OO is not about classes, it's about objects - FWIW, the
mere concept of 'class' is nowhere in the definition of OO, and some
OOPLs don't even have that concept (cf Self and Javascript).

Second point : in Python, everything (well... almost - at least
everything that can be bound to a name) is an object. So Python's
modules and functions are objects.

Third point : "top-level" (aka 'module level', aka 'globals') names
(names defined outside classes or functions) are in fact module
attributes. So, to make a long story short, you can consider a module as
a kind of a singleton.

What I wanted to point out here is that there's much more to OO than
what one learns with Java - and, FWIW, much more to Python's object
model than what it may seems at first.

Ah, and, BTW : welcome here !-)
 
C

christophertidy

Hi

I am new to Python and have recieved this error message when trying to
instantiate an object from a class from another file within the same
directory and wondered what I have done wrong.

I have a Step.py class:
class Step(object)
def __init__(self, sName):
"Initialise a new Step instance"
self.sName = sName
self.depSteps = []
self.remDepSteps = []
self.isCompleted = 0


Then I have created a new file within the same directory called
main.py:

import Step
a = Step("magn")

The following however generates the error
Traceback (most recent call last):
File "main.py", line 3, in ?
a = Step("magn")
TypeError: 'module' object is not callable

If anyone could help point me in the right direction, how to fix this
problem it would be much appreciated.
Chris
 
A

Amit Khemka

Hi

I am new to Python and have recieved this error message when trying to
instantiate an object from a class from another file within the same
directory and wondered what I have done wrong.

I have a Step.py class:
class Step(object)
def __init__(self, sName):
"Initialise a new Step instance"
self.sName = sName
self.depSteps = []
self.remDepSteps = []
self.isCompleted = 0


Then I have created a new file within the same directory called
main.py:

import Step
a = Step("magn")

The following however generates the error
Traceback (most recent call last):
File "main.py", line 3, in ?
a = Step("magn")
TypeError: 'module' object is not callable

If anyone could help point me in the right direction, how to fix this
problem it would be much appreciated.
Chris

The exception is being raised as you are being confused about the
names ie: you have a class named "Step" in a module named "Step.py" .
And by importing the module the only "Step" python sees is the module
not the names declared within the module.

To access a name defined in the module you can do :

example1:
import Step
a = Step.Step("magn") # It refers the name "Step" defined IN the module "Step"

example 2:
from Step import Step # You directly import the class ( and make the
name visible in your name space)
a = Step("magn")


Also have a look at:
http://effbot.org/zone/import-confusion.htm
http://docs.python.org/ref/import.html


Cheers,
 
L

Lawrence Oluyede

Hi

I am new to Python and have recieved this error message when trying to
instantiate an object from a class from another file within the same
directory and wondered what I have done wrong.

I have a Step.py class:
class Step(object)
def __init__(self, sName):
"Initialise a new Step instance"
self.sName = sName
self.depSteps = []
self.remDepSteps = []
self.isCompleted = 0

Then I have created a new file within the same directory called
main.py:

import Step
a = Step("magn")

The following however generates the error
Traceback (most recent call last):
File "main.py", line 3, in ?
a = Step("magn")
TypeError: 'module' object is not callable

This is because when you issue "import Step" you're actually importing
the "Step" _module_, not the "Step" class inside the module.

You can do this in at least two ways:

------
import Step
a = Step.Step("magn") # access the Step class inside Step module
------

or

------
from Step import Step # insert in the current namespace the Step class
a = Step("magn")
------
If anyone could help point me in the right direction, how to fix this
problem it would be much appreciated.
Chris

HTH
 
D

Diez B. Roggisch

Hi

I am new to Python and have recieved this error message when trying to
instantiate an object from a class from another file within the same
directory and wondered what I have done wrong.

I have a Step.py class:
class Step(object)
def __init__(self, sName):
"Initialise a new Step instance"
self.sName = sName
self.depSteps = []
self.remDepSteps = []
self.isCompleted = 0


Then I have created a new file within the same directory called
main.py:

import Step
a = Step("magn")

The following however generates the error
Traceback (most recent call last):
File "main.py", line 3, in ?
a = Step("magn")
TypeError: 'module' object is not callable

If anyone could help point me in the right direction, how to fix this
problem it would be much appreciated.

Do you by any chance come from a java-background?

Your actual problem is simply solved by this:


import Step

Step.Step("magn")

That's because Step.py is a module, and _not_ the class - there is no
file-class-correspondence as it is in e.g. Java.

Diez
 
B

Bruno Desthuilliers

Amit Khemka a écrit :
(snip)
The exception is being raised as you are being confused about the
names ie: you have a class named "Step" in a module named "Step.py" .

<nitpicking>
Actually, the module is named 'Step', not 'Setp.py' !-)
</nitpicking>
 
A

Amit Khemka

Amit Khemka a écrit :
(snip)

<nitpicking>
Actually, the module is named 'Step', not 'Setp.py' !-)
</nitpicking>
<humble-acknowledgment>
Yup, My Bad ! Thanks.
</humble-acknowledgment>
 
C

christophertidy

Thank you for your help that seems to have done the trick.
You are correct Diez B. Roggisch that I come from a java background!

I have a new tiny problem I can't understand either.
Withing Step.py I have the following method

def isCompleted(self):
"Check whether data step has been processed"
return self.isCompleted

Then within main.py I simply wish to print the value of isCompleted
which I try to do by the following
print 'Magn completed status is',a.isCompleted()

Which returns the following error:
a.isCompleted()
TypeError: 'int' object is not callable

I have tried ideas such as int(a.isCompleted) but to no prevail. Any
ideas?

Regards
Chris
 
D

Diez B. Roggisch

Thank you for your help that seems to have done the trick.
You are correct Diez B. Roggisch that I come from a java background!

I have a new tiny problem I can't understand either.
Withing Step.py I have the following method

def isCompleted(self):
"Check whether data step has been processed"
return self.isCompleted

Then within main.py I simply wish to print the value of isCompleted
which I try to do by the following
print 'Magn completed status is',a.isCompleted()

Which returns the following error:
a.isCompleted()
TypeError: 'int' object is not callable

I have tried ideas such as int(a.isCompleted) but to no prevail. Any
ideas?

Without more code, not really. It seems as if a is an integer, and not an
instance of Step.

Diez
 
B

Bruno Desthuilliers

(e-mail address removed) a écrit :
Thank you for your help that seems to have done the trick.
You are correct Diez B. Roggisch that I come from a java background!

I have a new tiny problem I can't understand either.
Withing Step.py I have the following method

def isCompleted(self):
"Check whether data step has been processed"
return self.isCompleted

Java background, indeed !-)

In Python, everything (including functions, methods, modules, classes
etc) is an object, and methods are just attributes like every others -
ie, there's no separate namespaces for methods. So when you set an
instance attribute 'isCompleted', it shadows the class attribute by the
same name.

The obvious solution is to give attributes different names. The perhaps
less obvious but much more pythonic solution is to get get rid of the
getter if all it does is returning the attribute. I know this sounds
strange when coming from Java, but there's no problem doing so - Python
has support for computed attributes (aka properties), so you can always
replace a plain attribute by a computed one latter if you need to do so,
this won't impact the client code.

HTH
 
W

Wildemar Wildenburger

Thank you for your help that seems to have done the trick.
You are correct Diez B. Roggisch that I come from a java background!

I have a new tiny problem I can't understand either.
Withing Step.py I have the following method

def isCompleted(self):
"Check whether data step has been processed"
return self.isCompleted
Java, ey? ;)

Why do you write a method that jut returns a variable anyway? Forget
that. Python doesn't need getters and setters.


Then within main.py I simply wish to print the value of isCompleted
which I try to do by the following
print 'Magn completed status is',a.isCompleted()

Which returns the following error:
a.isCompleted()
TypeError: 'int' object is not callable
That is (I think) because you have two things called "isCompleted" in
your class: The variable of type int (which BTW had better been of type
bool) and the method.
As I said, just scrap the method. In Python it's perfectly OK to expose
variables in the API. If you still want getters and setters, use look
into properties.

/W
 
D

Diez B. Roggisch

Thank you for your help that seems to have done the trick.
You are correct Diez B. Roggisch that I come from a java background!

I have a new tiny problem I can't understand either.
Withing Step.py I have the following method

def isCompleted(self):
"Check whether data step has been processed"
return self.isCompleted

Then within main.py I simply wish to print the value of isCompleted
which I try to do by the following
print 'Magn completed status is',a.isCompleted()

Which returns the following error:
a.isCompleted()
TypeError: 'int' object is not callable

I have tried ideas such as int(a.isCompleted) but to no prevail. Any
ideas?

The others spottet the error I missed. But I can offer something else:

http://dirtsimple.org/2004/12/python-is-not-java.html

It's a worthy read for someone coming from Java, needing time to adjust.

Diez
 
B

Bruno Desthuilliers

(e-mail address removed) a écrit :
(e-mail address removed) a écrit :
(snip)

Thanks guys
I have a list of lists such as
a = ["1" , "2"] b = ["4", "5", "6"] c = ["7",8", "9"]
Stored in another list: d = [a,b,c]
I know this makes me sound very stupid but how would I specify
in the parameter the inner lists without having to write them all out
such as:
for row in izip_longest(d[0], d[1], d[2], fillvalue='*'):
print ', '.join(row)
i.e. How could I do the following if I didn't know how many list of
lists I had.

for row in izip_longest(*d, fillvalue='*'):
print ', '.join(row)

HTH


I thought that but when I tried it I recieved a
"Syntax Error: Invalid Syntax"
with a ^ pointing to fillvalue :S
Yes, sorry - answered too fast, which is a cardinal sin. The
func(*sequence) is of course the right answer, but indeed you cannot
directly pass a keyword arg after it - you must either pass the keyword
args first:

izip_longest(fillvalue='*', *d)

or wrap it in a dict and use the ** notation:

izip_longest(*d, **dict(fillvalue='*'))

In this case, the second solution only makes sens if you already have
this dict for other reasons.
 
C

christophertidy

The others spottet the error I missed. But I can offer something else:

http://dirtsimple.org/2004/12/python-is-not-java.html

It's a worthy read for someone coming from Java, needing time to adjust.

Diez- Hide quoted text -

- Show quoted text -

That deffinately was a useful read, thanks.
Thankyou to everyone who sorted these problems for me, I have
progressed very well
with this python program throughout the day now.

I have another little question before I finish today:
I am currently struggling to use a global variable in my static
functions. I'll explain further

Within my main.py file I have

class Main(object):
stepStore = StepStore()

@staticmethod
def createDepSteps():
....
stepStore.addStep([bol7, pre5])
.......

@staticmethod
def processSteps():
for step in stepStore.stepList[:]:
......

Main.createDepSteps()
Main.processSteps()


Trying this approach I am getting a error saying with the
processSteps() method, stepStore is undefined
To solve this problem I am currently passing in the processSteps()
parameter a stepStore instance created within createDepSteps()
but there is surely a way stepStore can be a global attribute which
can be accessed from both methods?
Any help would be much appreciated again
Cheers
Chris
 
M

Marc 'BlackJack' Rintsch

Within my main.py file I have

class Main(object):
stepStore = StepStore()

@staticmethod
def createDepSteps():
....
stepStore.addStep([bol7, pre5])
.......

@staticmethod
def processSteps():
for step in stepStore.stepList[:]:
......

Main.createDepSteps()
Main.processSteps()


What's `Main` useful for? Is Java shining through again? A class with
just static methods isn't a class but just a container for functions. But
functions usually live in modules in Python so get rid of that class and
move the functions to module level.
Trying this approach I am getting a error saying with the
processSteps() method, stepStore is undefined

`stepStore` is searched in the function and then in the module. But it
is defined in the class. So you have to access `Main.stepStore`. Unless
you are modifying `stepStore.stepList` while iterating over it, you don't
need to make a copy by the way.

Ciao,
Marc 'BlackJack' Rintsch
 
D

Diez B. Roggisch

The others spottet the error I missed. But I can offer something else:

http://dirtsimple.org/2004/12/python-is-not-java.html

It's a worthy read for someone coming from Java, needing time to adjust.

Diez- Hide quoted text -

- Show quoted text -

That deffinately was a useful read, thanks.
Thankyou to everyone who sorted these problems for me, I have
progressed very well
with this python program throughout the day now.

I have another little question before I finish today:
I am currently struggling to use a global variable in my static
functions. I'll explain further

Within my main.py file I have

class Main(object):
stepStore = StepStore()

@staticmethod
def createDepSteps():
....
stepStore.addStep([bol7, pre5])
.......

@staticmethod
def processSteps():
for step in stepStore.stepList[:]:
......

Main.createDepSteps()
Main.processSteps()


Trying this approach I am getting a error saying with the
processSteps() method, stepStore is undefined
To solve this problem I am currently passing in the processSteps()
parameter a stepStore instance created within createDepSteps()
but there is surely a way stepStore can be a global attribute which
can be accessed from both methods?
Any help would be much appreciated again

You are deeeeep down in javaland again. first of all, with the exception of
factory methods, staticmethods or classmethods usually aren't needed. In
Python, you can define functions directly.

So move the above methods "toplevel", aka out of the class-context. and just
make stepStore a module-global variable.

Then things should work.

The distinction between staticmethod and classmethod is, that staticmethod
is a "pure" method, something unknown in Java.

the classmethod OTOH is a method that gets the class as first argument
(instead of the instance, as in an instance-method):

class Foo(object):
@classmethod
def bar(cls):
print cls

However: get rid of unnecessary classes. Java is severely limited regarding
the definition of "pure" code, the permanently needed class-context for
e.g. a main-method is absurd - to say the least.

Diez
 
B

Bruno Desthuilliers

(e-mail address removed) a écrit :
Thanks guys, I really appreciate it. I have never used google groups
before

Actually, comp.lang.python is a usenet newsgroup, not a google group.
Google only gives you a web fronted (and archives...) for that group. I
personnaly access it with my MUA.
and am so impressed with how helpful you all are. It is also lovely
that
none of you mock my little knowledge of Python but just want to
improve it.

Well... Why should we mock ? We've all been beginners, and we're still
all beginners in a domain or another.

But welcome to c.l.py and thanks for appreciating this group anyway !-)
I have another question in relation to the izip_longest function (I
persume
this should be within the same topic).
Using this funciton, is there a way to manipulate it so that the
columns can be formated
tabular i.e. perhaps using something such as str(list).rjust(15)
because currently the columns
overlap depending on the strings lengths within each column/list of
lists. i.e. my output is
currently like:

bo, daf, da
pres, ppar, xppc
magnjklep, *, dsa
*, *, nbi

But I want it justified, i.e:

bo , daf, da
pres , ppar, xppc
magnjklep, *, dsa
* , *, nbi

I am struggling to understand how the izip_longest function works

What's bothering you ?-)

Sorry, just joking. This code uses some 'advanced' stuffs like closures,
HOFs and generators/iterators, so it's obviously not that simple to grok
- FWIW, I myself had to read it at least thrice to understand it.
and thus don't really know how it could be manipulated to do the
above.

FWIW, you don't have - and IMHO should not try - to do this within
izip_longest, which is a generic function.
It would be much apprecited if somoene could also explain how
izip_function
works as I don't like adding code into my programs which I struggle to
understand.
Or perhaps I have to pad out the lists when storing the Strings?

I'd personnaly do the formatting just before printing.
 
C

Chris.Tidy

Thanks guys. Changing to how Python does things has a lot of geting
used to!
Do any of you have any ideas on the best way to do the following
problem:

Each loop I perform, I get a new list of Strings.
I then want to print these lists as columns adjacent to each other
starting with the first
created list in the first column and last created list in the final
column.

If you need any more information, just let me know!
Cheers
 
A

Amit Khemka

Thanks guys. Changing to how Python does things has a lot of geting
used to!
Do any of you have any ideas on the best way to do the following
problem:

Each loop I perform, I get a new list of Strings.
I then want to print these lists as columns adjacent to each other
starting with the first
created list in the first column and last created list in the final
column.

If you need any more information, just let me know!
Cheers

If I understand correctly what you may want is:

you can do:
assuming "\t" as the delimiter

or,
..... print i, '\t' , # note the trailing ","

If this is not what you want, post an example.

Btw, Please post new issues in a separate thread.

Cheers,
 
A

A.T.Hofkamp

Thanks guys. Changing to how Python does things has a lot of geting
used to!

That's part of the fun :)
Do any of you have any ideas on the best way to do the following
problem:

Each loop I perform, I get a new list of Strings.
I then want to print these lists as columns adjacent to each other
starting with the first
created list in the first column and last created list in the final
column.

Use zip:
x = ['1', '2']
y = ['3', '4']
for row in zip(x,y):
.... print ', '.join(row)
....
1, 3
2, 4


zip() constructs a list of rows, like

[('1', '3'), ('2', '4')]

which is then quite easy to print



Good luck,
Albert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,139
Latest member
JamaalCald
Top