-1

I'm currently going through the excellent Python koans and I can make sense of most of them with a bit of Googling but this one has me stumped (note: the __ variable is a placeholder for the answer I have to find):

class AboutTuples(Koan):

    # ....

    def test_tuples_of_one_look_peculiar(self):
        self.assertEqual(__, (1).__class__)
        self.assertEqual(__, (1,).__class__)
        self.assertEqual(__, ("Hello comma!", ))

I understand that __class__ returns the type of the expression, so in the first case this should be "a tuple containing an integer", and for the other two... I'm not quite sure, because of the comma after the first element. As it is, it fails and I get this output:

You have not yet reached enlightenment ...
    AssertionError: '-=> FILL ME IN! <=-' != <class 'int'>

This is the usual answer if you've left the placeholder variable. Following this, I tried the following:

self.assertEqual("<class 'int'>", (1).__class__)

But I get the following output:

You have not yet reached enlightenment ...
    AssertionError: "<class 'int'>" != <class 'int'>

So clearly it's not expecting a string, probably a type of some kind... how do I express this in Python? Is the answer similar for the other two test cases?

EDIT: Link to the exact koan, just in case

SolarBear
  • 4,534
  • 4
  • 37
  • 53
  • 3
    `self.assertEqual(int, (1).__class__)`? *"in the first case this should be "a tuple containing an integer""* - no, it absolutely shouldn't; that's what the exercise is trying to teach you to begin with. – jonrsharpe Feb 26 '17 at 14:46

1 Answers1

2

(1) is not a tuple; the parentheses are only there to disambiguate the attribute access from 1.__class__, which the parser would interpret as a malformed floating-point literal starting with 1..

(1,) is, however, a tuple. Tuples are defined by the comma, not the parentheses, which is why you can define a tuple with something like x = 1, 2. (The exception is the empty tuple, which is () rather than (,).)

Likewise, ("Hello, world!",) is a tuple containing one string.


As for what should replace the __, __class__ resolves to the class object associated with the object, not a string. You would use int and tuple, respectively, as the class objects returned by the two uses of __class__ in your example.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
chepner
  • 497,756
  • 71
  • 530
  • 681