5

I have a very simple class:

class Item(object):
    def __init__(self, guid, sku, name):
        self.guid = guid,
        self.sku = sku,
        self.name = name

When I create an object, such as:

item1 = Item('abc123', 1, 'abc1')

And I do:

print item1.guid

I get this as an output:

('abc123',)

Instead of the expected:

'abc123'

Any idea why it does this?

P.S.: name works as expected!

martineau
  • 119,623
  • 25
  • 170
  • 301
emihir0
  • 1,200
  • 3
  • 16
  • 39

2 Answers2

18
    self.guid = guid,   # Comma means create a tuple!
    self.sku = sku,
    self.name = name

You have done this yourself in your __init__ code. The tuple is constructed by a comma. Parentheses are just there to avoid ambiguity in some cases.

The correct code looks like this:

    self.guid = guid
    self.sku = sku
    self.name = name
Two-Bit Alchemist
  • 17,966
  • 6
  • 47
  • 82
6

Python isn't doing it, you are, right here:

self.guid = guid,
self.sku = sku,

Notice those trailing commas? In python, the , is actually what constructs tuples. So guid, is saying "make a tuple of size one with guid as the element". Remove the trailing commas and you're good to go.

Unfortunately the , operator is also the argument separator in function calls and inline initialization of lists/dicts, so typically you encounter "tuple construction" as (a,b). But the () are only there to let the interpreter disambiguate between the , tuple construction operator and the , argument delimiter. If you're not in a case where there is such ambiguity, like an assignment, the , operator is all you need, even if nothing comes after it.

aruisdante
  • 8,875
  • 2
  • 30
  • 37