Python Forum
Python 3 Function Annotations
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python 3 Function Annotations
#5
Or you type check yourself:
def increment(a):
    if not isinstance(a, int):
        raise ValueError('Can only increment int.')
    return a + 1
Another strategy is to force the int:
def increment(a):
    return int(a) + 1
This will accept strings, but turn them into ints if possible. If it's not possible, python will handle raising the error for you.

Either of these strategies requires checking for exceptions further up in the program with try/except blocks. In general, you should only be using these strategies when handling input you don't control. If you control the input, you need to make sure the input is right.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Messages In This Thread
Python 3 Function Annotations - by charlesprince - Feb-28-2017, 08:03 AM
RE: Python 3 Function Annotations - by stranac - Feb-28-2017, 10:35 AM
RE: Python 3 Function Annotations - by stranac - Mar-01-2017, 06:21 AM
RE: Python 3 Function Annotations - by ichabod801 - Mar-01-2017, 11:08 PM
RE: Python 3 Function Annotations - by ichabod801 - Mar-14-2017, 12:41 AM
RE: Python 3 Function Annotations - by wavic - Mar-14-2017, 03:01 AM
RE: Python 3 Function Annotations - by Larz60+ - Mar-14-2017, 05:43 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020