Search code examples
pythonpython-traitlets

is it possible to iterate a Tuple traitlets?


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 ?


Solution

  • 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