0

I'm create functions that receive as parameter an Int, an array of Int or a generator of Int

Eg.

def render(ids):
    for id in ids:
        ...

I made a function to manage it

def safecast_to_list(obj, force=False):
    try:
        if isinstance(obj, types.GeneratorType) and force:
            return list(obj)
        if not isinstance(obj, list | types.GeneratorType):
            return [obj]
        return obj
    except Exception:
        return []

def render(ids):
    ids = safecast_to_list(ids)
    for id in ids:
        ...

def foo(ids):
    ids = safecast_to_list(ids, force=True)
    ...
    return ids[0]

Is there any other solution that look better than mine ?

Faulheit
  • 116
  • 7
  • Why not just `if isinstance(ids, int): return [ids] else: return ids`? – Tomerikoo Jul 18 '22 at 09:56
  • @Tomerikoo I prefer to build something abstract as possible, if I have to use it for other types, the management of generator is also needed (sometimes I won't iterate over my var but just need to get the length or the first item) – Faulheit Jul 18 '22 at 10:03

0 Answers0