Python you want a string you get a tuple – howzat ?
Summary
How come you’re getting a tuple when you passed a string ?
Don’t do this at home
This is something that happened to me today. It really perplexed me so maybe this post will help someone else.
My class
I’d got a class a bit like the one below:
class cat(object): def __init__(self, name, colour, weight): self.name = name self.colour = colour, self.weight = weight def report(self): print self.name print self.colour print self.weight
Using it
But when I tried to use it like this:
mycat = cat('Garfield', 'Marmalade', 10) mycat.report()
the output looked like this :
Garfield ('Marmalade',) 10
The problem being the attribute `colour` was being stored as a tuple.
The Answer
Looking back on it the problem is quite obvious but I was so busy looking at other parts of the situation (which was significantly more complex than the my cat
example I missed it for quite a while.
Within the __init__
method I had inadvertently appended a comma onto the end of the self.colour
assignment and Python takes that to mean, in our example, colour
is the first element of a tuple.