-1

I want to check whether user called function by passing any argument or not.

here is my function

def HEXtoRGB(hexlist):

    rgblist = []
    for i in range(len(hexlist)):
        h = hexlist[i].lstrip('#')
        rgb = tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
        rgblist.append(rgb)

    return(rgblist)


print(HEXtoRGB())

HEXtoRGB() takes hexlist as a paramter. if user called HEXtoRGB() function without argument then error message should print. for that i tried error handling in python but its not working

def HEXtoRGB(hexlist):

    try:
        rgblist = []
        for i in range(len(hexlist)):
            h = hexlist[i].lstrip('#')
            rgb = tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
            rgblist.append(rgb)
    
        return(rgblist)
    except:
        print("Hex Color List Not Found")

print(HEXtoRGB())

above exception handling gives me same error

  File "test.py", line 10, in <module>
    print(HEXtoRGB())
TypeError: HEXtoRGB() missing 1 required positional argument: 'hexlist'

Is there any best way to handle missing argument error, In case user called function without argument

Mayur Satav
  • 985
  • 2
  • 12
  • 32
  • Can you please clarify what you are trying to achieve? ``def HEXtoRGB(hexlist):`` already means that ``HEXtoRGB`` *must* be called with an argument, and it is an error to call ``HEXtoRGB()`` – as the ``TypeError`` shows. What other behaviour do you want? – MisterMiyagi Jun 29 '20 at 14:06
  • want to handle type error, so that next time user can pass argument – Mayur Satav Jun 29 '20 at 14:08
  • It's the user making the error of calling ``HEXtoRGB`` wrongly, and *they* have to handle it. The user *can* already handle the error and pass an argument the next time. If ``HEXtoRGB`` internally handles the error, the user gets no immediate notification that they did something wrong and might limp on with an incorrect result. What behaviour do you expect to present to the user? – MisterMiyagi Jun 29 '20 at 14:11
  • 2
    `def HEXtoRGB(hexlist==None):` and then test for `if not(hexlist)` – Serafim Jun 29 '20 at 14:11
  • Does this answer your question? [Best way to check function arguments?](https://stackoverflow.com/questions/19684434/best-way-to-check-function-arguments) – Alok Jun 29 '20 at 14:12
  • Sometimes my fingers are a bit too swift. There is an extra `=` in my comment above. – Serafim Jun 29 '20 at 20:43

1 Answers1

0

You can give a default value for the parameter, e.g.:

def HEXtoRGB(hexlist=None):
    if hexlist is None:
        print("Hex Color List Not Found")
    else:
        rgblist = []
        for i in range(len(hexlist)):
            h = hexlist[i].lstrip('#')
            rgb = tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
            rgblist.append(rgb)
        return(rgblist)

print(HEXtoRGB())

Note that None will be the return value in this case. You might want to return something else.

Serafim
  • 484
  • 3
  • 10