-1

In Python methods are a bit strange, at least compared to other languages. A function, say in C++, goes something like so:

void foo(int i){
    cout << i*2 << "\n";
}

This ensures that the object passed into that function is in fact an integer. However in Python the same function looks like this:

def foo(i):
    print i*2

This function doesn't require i to be an integer, let alone a number. You could even pass in a string. So my question is: what is the general approach for handling this when writing code? Generally speaking, is it better to check the type and throw an error message if used incorrectly or is it preferred to no check at all and assume the correct type has been passed?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 2
    Have you read e.g. https://docs.python.org/3/glossary.html#term-duck-typing? There are plenty of related questions on SO, too: http://stackoverflow.com/q/11328920/3001761 is a start. – jonrsharpe Apr 13 '15 at 20:20
  • Also, checking the type and throwing an error is quite pointless, since it will throw an error anyway if the type is not compatible. – wvdz Apr 13 '15 at 20:23
  • Seems like you have never heard of a dynamically-typed language. Python is hardly the only one: Javascript and Ruby are two others you may come across, but there are many many more. – Daniel Roseman Apr 13 '15 at 20:23
  • Don't even check the type - just do the calculation. If you think it might fail (due to taking user input, for example), [`try`](https://docs.python.org/3.4/tutorial/errors.html) it and catch the error if it fails, because it's easier to ask for forgiveness than permission. – TigerhawkT3 Apr 13 '15 at 20:24
  • To the users suggesting "just let it fail naturally if the input is bad", it's possible that bad input will produce unusual output instead of crashing. For instance, `foo("42")` will print "4242" rather than raising a TypeError or anything. – Kevin Apr 13 '15 at 20:26
  • Python guarantees that it's an object. But functions and classes are objects, too. :) – Jim Dennis Apr 13 '15 at 20:28

2 Answers2

1

This is subjective. The easiest way to ensure that your arguments are of the proper type is with an assert statement -- in your example, something like assert isinstance(i, int), "foo expects an int!" But this isn't strictly necessary -- if it won't run with the erroneous arguments, it'll throw an error all the same.

In short, do what helps you to debug best.

Greg Edelston
  • 534
  • 2
  • 12
  • 1
    just to add, if you prefer more speed than `assert` or `isinstance`, use `type(object)` for readability or `object.__class__` for performance. – Tcll Jun 23 '17 at 13:39
0

With Python, you want to handle this situation by verifying the input with:

try:
   val = int(userInput)
except ValueError:
   print("That's not an int!")

This is trying to convert the user input to an integer, and if it's unable to be converted, it throws a ValueError.

Joe Bruno
  • 11
  • 1
  • What's wrong with this answer? – TigerhawkT3 Apr 13 '15 at 20:25
  • you can check the error like this in python, because in c++ and other static languages it will still throw an exception if the value passed into the function is not an integer – danidee Apr 13 '15 at 20:27
  • It seems like you're answering the question "how can I tell if a string can successfully be turned into an integer?" when the OP is asking "how do I tell if a variable is the type I think it is?". "int(x) doesn't crash" does not imply "x is an int". – Kevin Apr 13 '15 at 20:30
  • I think the idea may have been to check whether something is sufficiently close to an `int` to be passed to `foo()` for the expected result. – TigerhawkT3 Apr 13 '15 at 20:35
  • Actually, this *suppresses* the `ValueError`; so what happens when `val` is used afterwards as if it was an `int`? – jonrsharpe Apr 13 '15 at 20:36
  • Presumably there will be more logic to decide whether to send `val` to `foo()` or do something else (send it to another function, ask for more input, etc.). – TigerhawkT3 Apr 13 '15 at 20:47
  • problem with this is `except` is generally many times slower than `else`. – Tcll Jun 23 '17 at 13:36