How can I avoid type checking a python object if its attributes aren't used? -


i've come across answers here type checking in general, type checking numbers, , type checking strings. people seem respond saying type checking should never performed in python (< 2.6) due duck typing. (limited) understanding of duck typing type determined use of object's attributes. do if i'm not using attributes?

i have simple function determines constants based on argument, should number. raise exception defined by

class outofboundserror(valueerror):     """     specified value outside domain.     """ 

with message telling them number gave me big. keep message specific. if argument string (like 'charlie'), still considers argument greater specified number (and raises exception). should add dummy line code argument + 2 typeerror raised?

note: don't know abcs don't think they're available me since latest python version have access 2.5 : (.

a common duck-typish python solution problem (try to) convert got need. example, if need integer:

def getconstants(arg):     try:         arg = int(arg)     except:         raise typeerror("expected integer, or can converted one, got " + repr(arg)) 

the int type constructor knows how deal many built-in types. additionally, types convertible int type can implement __int__() special method, allow them used here. if user passed in string, work fine long contained digits.

your idea of performing operation performed on numeric type (such adding 2) similar, , work great in many cases, fail strings can converted desired type, type conversion better.

you without try/except here, since int() raise either typeerror or valueerror if can't conversion, think typeerror more appropriate since mainly interested in object's type, chose catch exception , raise typeerror.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -