A real Python parse integer function

Posted on Wed 21 September 2011 in blog

Is anyone else annoyed by the fact that int() in python is retarded and can't tell the difference between decimal, hex, and octal?

Your solution:

def parseint(val):
    if isinstance(val, int):
        return val
    if not isinstance(val, (unicode,str)):
        return None

    try:
        if val.startswith('0x'):
            return int(val, 16)
        if val.startswith('0'):
            return int(val, 8)
        return int(val)
    except ValueError:
        return None

Hope this helps someone.