Consider
tuple('a') # tuple ('a',)
('a',) # tuple
tuple(1) # TypeError: ‘int’ object is not iterable
(1,) # tuple
(1) # 1 (expresion)
[1] # list
list(1) # TypeError: ‘int’ object is not iterable
list('a') # list ['a']
Is there a reason why tuple() and list() accept iterable only?
Why not to test if parameter isinstance of Iterable and return one item tuple/list instead?
Or why a character (scalar/singlechar string) is iterable and scalar int not?
Make int iterable:
class IterableInt(int):
def __iter__(self):
yield int(self) # or: yield self
i = IterableInt(7)
list(i) # [7]
tuple(i) # (7,)
sum(i) # 7
for x in i:
print(x) # 7
The idea came from filling data for api request from any user input:
month = 8 # or None or (7,8)
request = {
"month": [f"{m:02}" for m in ((month,) if month else range(1, 13))],
# Ideally: … in (month if month else …
# [f"{m:02}" for m in (month if isinstance(month, Iterable) else (month,) if …
}
# {"month: ['08']}
Is there a reason why int is not iterable returning itself? In contrast to iterable single character…
Thank you in advance.