1

I have an imaginary class:

class Foo: def __init__(self, **values): self._value_tuple = tuple(values.items()) 

And I would like to be able to convert it to tuple using built-in constructor:

>>> foo = Foo(ham=1, eggs=2, spam=3) >>> tuple(foo) (('ham', 1), ('eggs', 2), ('spam', 3)) 

*I know I can to it manually, by implementing a method like astuple(). I would like to, if possible, achieve it by calling tuple constructor.

1 Answer 1

3

You can achieve desired functionality by defining __iter__() method in your class:

class Foo: def __init__(self, **values): self._value_tuple = tuple(values) def __iter__(self): return self._value_tuple.__iter__() # or return iter(self._value_tuple) foo = Foo(ham=1, eggs=2, spam=3) print(tuple(foo)) 

Output:

('ham', 'eggs', 'spam') 

If you want (keys, values), you can store your items in dict:

class Foo: def __init__(self, **values): self._value_dict = values def __iter__(self): return iter(self._value_dict.items()) foo = Foo(ham=1, eggs=2, spam=3) print(tuple(foo)) 

Prints:

(('ham', 1), ('eggs', 2), ('spam', 3)) 

__iter__() is part of Python Datamodel. When you implement this method in your class, all functions and syntax constructs that expect something iterable will work with your class without change, that includes parameters in tuple().

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

3 Comments

Cool, this works. (values.items() instead of values though, I've updated my answer). Can you please explain why __iter__ gives me this functionality? It seems pretty magical right now. (Why __iter__ of all the dunder methods)
@AnriofAstora tuple() consumes an iterable object.
Oh, ok, I get it. Thank you for the responses.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.