0

I transformed some of my lib variable into traitlets and I'm facing an error when iterating on a Tuple even though this is possible with built-in tuple.

from traitlets import Tuple

a = Tuple((1,2,4)).tag(sync=True)
for i in a:
    print(i)

>>> ---------------------------------------------------------------------------
>>> TypeError                                 Traceback (most recent call last)
>>> /Users/pierrickrambaud/Documents/travail/FAO/app_buffer/sepal_ui/untitled.ipynb >>> Cellule 14 in <cell line: 1>()
>>> ----> 1 for i in a: 
>>>       2     print(i)
>>>  
>>> TypeError: 'Tuple' object is not iterable

with the normal tuple:

a = (1, 2, 3)
for i in a: 
    print(i)

>>> 1
>>> 2
>>> 3

Is it a bug or is it the intended behavior ?

Pierrick Rambaud
  • 1,726
  • 1
  • 20
  • 47
  • "Is it a bug or is it the intended behavior ?" only the writers of the module can answer definitively, but more likely than not it is intended behavior. It isn't that hard to implement `__next__` and `__iter__` and I would be surprised if it was simply an oversight that they didn't. In many applications of tuples, iterating over them is something which lacks a clear meaning. – John Coleman Dec 27 '22 at 17:18
  • @JohnColeman [Even the list variant](https://github.com/ipython/traitlets/blob/47e652f96aff54d1aa3b19337c9c8d80fe0fd4c4/traitlets/traitlets.py#L2959) lacks iteration. So ya, it appears the classes just aren't meant to be used in this way. – Carcigenicate Dec 27 '22 at 17:30

1 Answers1

0

The answer is yes of course.

The issue I was getting in my application were due to a typo and the bug is only a side effect, For future reader the small example I gave is not showing the behaviour of a trait as it should be used. Instead create the trait in a class extending HasTraits:

from traitlets import Tuple, HasTraits

class A(HasTraits):
    toto = Tuple((1,2,3))

a = A() 
for i in a.toto:
    print(i)


>>> 1
>>> 2
>>> 3
Pierrick Rambaud
  • 1,726
  • 1
  • 20
  • 47