-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.

4
  • 1
    Where exactly did you get the idea to implement a __tuple__ method? It's not in the data model. This is the behaviour you should have expected. Commented Oct 19, 2017 at 19:28
  • 3
    There's no way print(tuple(ex)) printed [3, 2]. That's not a tuple. Commented Oct 19, 2017 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. Commented Oct 19, 2017 at 19:33
  • It is closed. Commented Oct 19, 2017 at 19:42

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Because __str__() exists.
@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 New vocab term: dunder methods. Never knew. Friend kept referring to them as "magic" declarations.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.