Description:
I’ve read a lot opinions about checking value type in python and most said that you shouldn’t check type, but instead use try and except.
I want to make clear few things.
Questions:
When I have method like this:
def set_age(self, age):
self._age = age
I can’t let user pass any types other then int because later in code it can cause some harder to debug bugs.
And according to Python methodology I can’t check type.
So how should I do it with try in the proper way?
def set_age(self, age):
try:
age = int(age)
except TypeError:
raise TypeError('First parameter must be of int type.')
self._age = age
Or just
def set_age(self, age):
self._age = int(age)
and let Python raise errors on it’s own.
I know it might be silly questions, I just want to make sure.
Python will raise an appropriate error if it’s not an integer, so there is no need to put your own over the top of it.
Let’s step back a bit though, as there are other problems here. getters and setters are really unpythonic – either just use an attribute, or use properties.
In this case, I think you are still thinking in the wrong way. The reason we don’t type check in Python is because we shouldn’t care what type something is, just if it will work in the given situation. Making everything the type you think it should be as soon as you get it is essentially type checking.
You say it will make it harder to debug, but that’s not really the experience most people have. Duck typing is designed to allow anything that can do the job do the job. Converting everything to an
intlimits your program. The problem isn’t here, the problem is with your code that is passing something that doesn’t make sense to your class. In my experience, this is actually a really rare thing to do – you don’t tend to throw random stuff at classes and see what sticks.So, my suggestion here is that you use an attribute – just do
x.age = ...instead of usingset_age()or anything like that. If you really need to have anint(as in, only whole numbers make sense), then use a property and callint()in the setter, leaving the error to propagate to the caller if it happens.