TransWikia.com

How to manage special cases?

Stack Overflow Asked on December 20, 2021

I have some function that needs to return a non-negative integer after doing some calculation. However, there is some special cases where this calculation is not possible. I decided to "flag" them with different negative integers (as I need to distinguish between those special cases later). I am wondering if this is a bad practice. Intuitively, if I want to use the result returned by this function in another function, I can do some mistakes with those negative values. What do you think? Is there a better way to do it?

def some_function(...)->int:

    if A:
        # do some calculation

        if B: 
            # do some calculation
            return meaningful_result
        
        else:
            try:
                # do some calculation

                if C:
                    # do some calculation
                    return meaningful_result
                else:
                    return -1 # -1 is somehow used to "flag" a first special case 
            
            except LookupError:
                return -2 # -2 is somehow used to "flag" a second special case 
    else: 
        return -3 # -3 is somehow used to "flag" a third special case 

One Answer

What do you think? Is there a better way to do it?

If you had only one special case I would say to return None. But in this case since you need to distinguish them it's better to give something more meaningful, like a descriptive string, than some arbitrary magical number. And you can update the return type hint to be Union[str, int].

ps: you will need from typing import Union in this case

Answered by Hemerson Tacon on December 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP