-2

In a custom object with __iter__() defined, when calling tuple(obj), it returns the data of __iter__() in tuple form, but I want it to return from __tuple__().

This is a really big class, and I don't want to paste it here. I instead wrote a smaller example of my problem.

class Example:
    def __init__(self, a, b):
        self.data = [a, b]

    def __iter__(self):
        return iter(reversed(self.data))

    def __tuple__(self):
        return map(str, self.data)


ex = Example(2, 3)

print([x for x in ex])  # Should return the data from __iter__().
>>> [3, 2]  # Reversed, good...

print(tuple(ex))  # Now calling: __tuple__().
>>> (3, 2)  # Should have returned ["2", "3"].

If you need to see all of my code, ask, and I'll put it in a Pastebin. I just wanted to save you the effort of sorting through all of those extra methods.

Does __iter__() override the __tuple__() type? For some reason I can't get it to change to return what it should from __tuple__().

Thanks in advance.

Jacob Birkett
  • 1,927
  • 3
  • 24
  • 49
  • 1
    Where exactly did you get the idea to implement a `__tuple__` method? It's not in the [data model](https://docs.python.org/3/reference/datamodel.html). This is the behaviour you should have expected. – jonrsharpe Oct 19 '17 at 19:28
  • 3
    There's no way `print(tuple(ex))` printed `[3, 2]`. That's not a tuple. – user2357112 Oct 19 '17 at 19:29
  • Please vote to close this because it would destroy my rep if it stays. I had assumed that `__tuple__()` existed, and to be honest never thought it wouldn't. After all, `__str__()` exists. – Jacob Birkett Oct 19 '17 at 19:33
  • It *is* closed. – jonrsharpe Oct 19 '17 at 19:42

1 Answers1

4

__tuple__ isn't a thing. tuple doesn't look for a __tuple__ method to perform conversion-to-tuple. I don't know where you got that idea.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Because `__str__()` exists. – Jacob Birkett Oct 19 '17 at 19:29
  • 2
    @spikespaz, an understandable chain of reasoning. "`__str__` and `__int__` exist, so maybe there are dunder methods for every built-in type", one might think. But this turns out not to be the case. – Kevin Oct 19 '17 at 19:32
  • @Kevin New vocab term: dunder methods. Never knew. Friend kept referring to them as "magic" declarations. – Jacob Birkett Oct 19 '17 at 19:34
  • @spikespaz: Note that the dunders are just a naming convention; any "magic" of magic methods doesn't have anything to do with the underscores. For example, `next` was the magic method for retrieving an item from an iterator on Python 2. – user2357112 Oct 19 '17 at 19:39