Is it a clean way to implement a kind of "__tuple__" method?

python, python-3.x

Solution

The built-in `tuple()` is not designed as a point of customization for your classes. As far as I know there is no customization point for conversion to tuple.

So instead you've used a designed point of customization, the `iter()` built-in and corresponding `__iter__` method. That's fine as far as it goes, but it does both less and more than you want:

- More because it allows anyone to iterate over your object, not just `tuple()`.

- Less because although `tuple` detects the case its argument is a tuple, it doesn't detect the case it returns a tuple-iterator from `__iter__`. So as you've seen it copies the tuple.

Since there is no way to directly customize the effect of passing your object to `tuple()` (unlike `iter()` or `len()` or many others), you basically can't use the `tuple()` function as the way to access `self.my_tuple`. All you can do is make it return a copy.

Based on your comment:

I have several attributes for instance a.b, a.c, a.d and I would like to be able to do tuple(a) to get (b,c,d)

You could perhaps make use of `collections.namedtuple`:

class A(collections.namedtuple('A', 'b c d')):
    # whatever methods you need

Of course this means those attributes of `A` are immutable, so if that's not what you want then it's not helpful.

Problem

Let that an object a of a class A has an attribute ".my_tuple". I want to be able to get this attribute calling. ``` tuple(a) ``` the simplier way I found is to define A such as: ``` class A(): # other things def __iter__(self): return self.my_tuple.__iter__() ``` But it seems a little dirty : what I understand is that "tuple(a)" will iterate over self.my_tuple in order to construct a copy of it, while I only want a pointer on it... Is the built-in "tuple" optimized to deal with those cases ? If not, is it a best way to do that (an keep it "pythonic" : in my case it make sense to cast A-type into tuple).

Original source