On Wednesday, September 21, 2016 at 10:27:15 AM UTC-4, Sayth Renshaw wrote:
> Trying to clarify why ints and strings arent treated the same.
> You can get a valuerror from trying to cast a non-int to an int as in
> int(3.0) however you cannot do a non string with str(a).
> Which means that you likely should use try and except to test if a user
> enters a non-int with valuerror.
> However as you can't str () and get a valuerror you use conditional logic
> with strings.
> Therefore to try and keep with pythons only one obvious way of doing things
> should i prefer conditional logic for all using isinstance?
> That way regardless of input type my code flows the same and more explicitly
> states the intended type.
How you do your check depends a lot on why you are checking, how strange a
value you expecting to be checking, and what you want to do if the value
isn't good for you. Can you give us specifics of the check you are doing,
and the values you want to accept/reject, and the behavior you want on
int() and str() are not casts, they are conversions, or constructors, and
they have different ideas of the kinds of things they can turn into ints
One Python philosophy is to not check types just to reject values, but
instead to work with the value you are given. This gives the caller the
flexibility to provide a value of a type perhaps you didn't expect, but
which will work fine anyway.