Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the best way to work with unique item, list and generator

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

Even though Python does not support function overloading out of the box there is a way to do it yourself:
https://stackoverflow.com/a/67830038/10547647

Or use third party library:
https://github.com/bintoro/overloading.py

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading