By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,536 Members | 2,165 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,536 IT Pros & Developers. It's quick & easy.

TypeError: 'module object is not callable'

P: n/a
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

Sep 3 '07 #1
Share this Question
Share on Google+
33 Replies


P: n/a
On 9/3/07, ch*************@hotmail.com <ch*************@hotmail.comwrote:
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,

--
----
Amit Khemka
website: www.onyomo.com
wap-site: www.owap.in
Sep 3 '07 #2

P: n/a
On Sep 3, 10:48 am, christophert...@hotmail.com wrote:
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

Sep 3 '07 #3

P: n/a
ch*************@hotmail.com wrote:
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
Sep 3 '07 #4

P: n/a
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>

Sep 3 '07 #5

P: n/a
On 9/3/07, Bruno Desthuilliers
<br********************@wtf.websiteburo.oops.comwr ote:
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>
<humble-acknowledgment>
Yup, My Bad ! Thanks.
</humble-acknowledgment>
--
----
Amit Khemka
website: www.onyomo.com
wap-site: www.owap.in
Sep 3 '07 #6

P: n/a
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

Sep 3 '07 #7

P: n/a
ch*************@hotmail.com wrote:
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
Sep 3 '07 #8

P: n/a
ch*************@hotmail.com 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
Sep 3 '07 #9

P: n/a
ch*************@hotmail.com wrote:
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
Sep 3 '07 #10

P: n/a
ch*************@hotmail.com wrote:
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
Sep 3 '07 #11

P: n/a
>
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

Sep 3 '07 #12

P: n/a
On Mon, 03 Sep 2007 16:13:28 +0000, christophertidy wrote:
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
Sep 3 '07 #13

P: n/a
ch*************@hotmail.com wrote:
>
>>
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
Sep 3 '07 #14

P: n/a
ch*************@hotmail.com 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 !-)
Sep 3 '07 #15

P: n/a
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

Sep 4 '07 #16

P: n/a
On 9/4/07, Ch********@jet.uk <Ch********@jet.ukwrote:
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:
>>l = ['1', '2', '3', '4']
you can do:
>>print "\t".join(l) # lookup join method in string module,
assuming "\t" as the delimiter

or,
>>for i in l:
..... 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,
--
----
Amit Khemka
website: www.onyomo.com
wap-site: www.owap.in
Sep 4 '07 #17

P: n/a
On 2007-09-04, Ch********@jet.uk <Ch********@jet.ukwrote:
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
Sep 4 '07 #18

P: n/a
On Sep 4, 11:24 am, "Amit Khemka" <khemkaa...@gmail.comwrote:
On 9/4/07, Chris.T...@jet.uk <Chris.T...@jet.ukwrote:
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:
>l = ['1', '2', '3', '4']

you can do:
>print "\t".join(l) # lookup join method in stringmodule,

assuming "\t" as the delimiter

or,
>for i in l:

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

If this isnotwhat you want, post an example.

Btw, Please post new issues in a separate thread.

Cheers,
--
----
Amit Khemka
website:www.onyomo.com
wap-site:www.owap.in
I think that is very similar to what I want to do.
Say I had lists a = ["1" , "2", "3"] b = ["4", "5", "6"] c = ["7",
"8", "9"]
Stored in another list d = [a,b,c]
I want the printed output from d to be of the form:
1 4 7
2 5 8
3 6 9
>From what I am aware, there is no table module to do this. The '\t'
operator looks like it can allow this,
I am playing with it at the moment, although going for my lunch break
now!

Sep 4 '07 #19

P: n/a
On 9/4/07, cj***@bath.ac.uk <cj***@bath.ac.ukwrote:
On Sep 4, 11:24 am, "Amit Khemka" <khemkaa...@gmail.comwrote:
On 9/4/07, Chris.T...@jet.uk <Chris.T...@jet.ukwrote:
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:
>>l = ['1', '2', '3', '4']
you can do:
>>print "\t".join(l) # lookup join method in stringmodule,
assuming "\t" as the delimiter

or,
>>for i in l:
.... print i, '\t' , # note the trailing ","

If this isnotwhat you want, post an example.

Btw, Please post new issues in a separate thread.

Cheers,
--
----
Amit Khemka
website:www.onyomo.com
wap-site:www.owap.in

I think that is very similar to what I want to do.
Say I had lists a = ["1" , "2", "3"] b = ["4", "5", "6"] c = ["7",
"8", "9"]
Stored in another list d = [a,b,c]
I want the printed output from d to be of the form:
1 4 7
2 5 8
3 6 9
From what I am aware, there is no table module to do this. The '\t'
operator looks like it can allow this,
I am playing with it at the moment, although going for my lunch break
now!
Have a look at function 'zip' or function 'izip' in module "itertools" .

--
----
Amit Khemka
website: www.onyomo.com
wap-site: www.owap.in
Sep 4 '07 #20

P: n/a
"A.T.Hofkamp" <ha*@se-162.se.wtb.tue.nlwrote:
>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
But watch out if the lists aren't all the same length: zip won't pad out
any sequences, so it may not be exactly what is wanted here:
>>x = ['1', '2', '3']
y = ['4', '5']
for row in zip(x,y):
print ', '.join(row)
1, 4
2, 5
>>>
Sep 4 '07 #21

P: n/a
But watch out if the lists aren't all the same length: zip won't pad out
any sequences, so it maynotbe exactly what is wanted here:
>x = ['1', '2', '3']
y = ['4', '5']
for row in zip(x,y):

print ', '.join(row)

1, 4
2, 5
Unfortunately the lists will be of different sizes
By the way I apologise for different questions within the same thread.
When I have another question, I will make a new topic
Sep 4 '07 #22

P: n/a
cj***@bath.ac.uk wrote:
>But watch out if the lists aren't all the same length: zip won't pad out
any sequences, so it maynotbe exactly what is wanted here:
>>x = ['1', '2', '3']
y = ['4', '5']
for row in zip(x,y):

print ', '.join(row)

1, 4
2, 5

Unfortunately the lists will be of different sizes
In that case use:

from itertools import repeat, chain, izip
def izip_longest(*args, **kwds):
fillvalue = kwds.get('fillvalue')
def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
yield counter() # yields the fillvalue, or raises IndexError
fillers = repeat(fillvalue)
iters = [chain(it, sentinel(), fillers) for it in args]
try:
for tup in izip(*iters):
yield tup
except IndexError:
pass
x = ['1', '2', '3']
y = ['4', '5']
for row in izip_longest(x,y, fillvalue='*'):
print ', '.join(row)
which gives:

1, 4
2, 5
3, *
(izip_longest is in a future version of itertools, but for
now you have to define it yourself).

Sep 4 '07 #23

P: n/a
On Sep 4, 2:06 pm, Duncan Booth <duncan.bo...@invalid.invalidwrote:
cj...@bath.ac.uk wrote:
But watch out if the lists aren't all the same length: zip won't pad out
any sequences, so it maynotbe exactly what is wanted here:
>x = ['1', '2', '3']
y = ['4', '5']
for row in zip(x,y):
print ', '.join(row)
1, 4
2, 5
Unfortunately the lists will be of different sizes

In that case use:

from itertools import repeat, chain, izip
def izip_longest(*args, **kwds):
fillvalue = kwds.get('fillvalue')
def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
yield counter() # yields the fillvalue, or raises IndexError
fillers = repeat(fillvalue)
iters = [chain(it, sentinel(), fillers) for it in args]
try:
for tup in izip(*iters):
yield tup
except IndexError:
pass

x = ['1', '2', '3']
y = ['4', '5']
for row in izip_longest(x,y, fillvalue='*'):
print ', '.join(row)

which gives:

1, 4
2, 5
3, *

(izip_longest is in a future version of itertools, but for
now you have to define it yourself).
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.
Sorry this sounds stupid and easy.
Thankyou very much in advance as well, you are all very helpful
indeed.

Sep 4 '07 #24

P: n/a
cj***@bath.ac.uk 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
Sep 4 '07 #25

P: n/a
On Sep 4, 3:20 pm, Bruno Desthuilliers <bruno.
42.desthuilli...@wtf.websiteburo.oops.comwrote:
cj...@bath.ac.uk 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

Sep 4 '07 #26

P: n/a
On Sep 4, 3:20 pm, Bruno Desthuilliers <bruno.
42.desthuilli...@wtf.websiteburo.oops.comwrote:
cj...@bath.ac.uk 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"
message with ^ pointing to the 'e' of fillvalue

Sep 4 '07 #27

P: n/a
cj***@bath.ac.uk writes:
>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
Python isn't too happy about adding individual keyword arguments after
an explicit argument tuple. Try this instead:

for row in izip_longest(*d, **dict(fillvalue='*')):
print ', '.join(row)
Sep 4 '07 #28

P: n/a
On 9/4/07, Hrvoje Niksic wrote:
Python isn't too happy about adding individual keyword arguments after
an explicit argument tuple. Try this instead:

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

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

-Miles
Sep 4 '07 #29

P: n/a
cj***@bath.ac.uk a écrit :
On Sep 4, 3:20 pm, Bruno Desthuilliers <bruno.
42.desthuilli...@wtf.websiteburo.oops.comwrote:
>>cj...@bath.ac.uk 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.
Sep 4 '07 #30

P: n/a
Thanks guys, I really appreciate it. I have never used google groups
before
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.

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
and thus don't really know how it could be manipulated to do the
above.
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?

Any help would be much appreciated.

Sep 5 '07 #31

P: n/a
On 9/5/07, cj***@bath.ac.uk <cj***@bath.ac.ukwrote:
Thanks guys, I really appreciate it. I have never used google groups
before 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.
And we are proud of it !
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
You can format the output while "print"ing the table. Have a look at:

http://www.python.org/doc/current/li...q-strings.html

example:
for tup in izip_longest(*d, **dict(fillvalue='*')):
print "%15s, %15s, %15s" %tup # for a tuple of length 3, you can
generalize it

I am struggling to understand how the izip_longest function works
and thus don't really know how it could be manipulated to do the
above.
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?

Any help would be much appreciated.
This is an example of "generator" functions, to understand what they
are and how they work you can:
1. web-search for "python generators"
2. have a look at "itertools" module, for more generators

--
----
Amit Khemka
website: www.onyomo.com
wap-site: www.owap.in
Sep 5 '07 #32

P: n/a
On Behalf Of cj***@bath.ac.uk
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
Once you have a nice rectangular list of lists, you might want to take a
look at my padnums module.

# Usage:
import padnums
import sys

table = [row for row in izip_longest(*d, fillvalue='*')]
padnums.pprint_table(sys.stdout, table)

Code described here, with link to module:
http://ginstrom.com/scribbles/2007/0...ble-in-python/

Regards,
Ryan Ginstrom

Sep 5 '07 #33

P: n/a
cj***@bath.ac.uk 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.
Sep 5 '07 #34

This discussion thread is closed

Replies have been disabled for this discussion.