0

The question is related to good and bad practice: From C programming I'm used to check passed arguments at the begin of a function, thereby returning an error-code when something is wrong (e.g. a NULL pointer).

In Python an exception will be raised automatically, when, lets say, a passed Queue object is None or of wrong type and one tries to operate on this invalid queue object. Is it good practice to check datatypes in advance like

def foo(queue):
    if issubclass(Queue, arg):
        raise ...
    # ...

or should the error handling rather be left as a task for the calling function, because something was wrong there? I'm tempted to do it in the first way, but feel, that it might bee wrong.

3
  • 1
    I would think all good functions and modules should have in-built error handling methods. Commented Oct 11, 2017 at 8:23
  • 1
    Apart from anything else, the whole point of duck typing is that you shouldn't test that something is a subclass of any particular type. If you need to check anything at all, you would check that it has the attributes or methods you need to call. Commented Oct 11, 2017 at 8:25
  • 1
    I think failing early is good practice for any language. Commented Oct 11, 2017 at 8:25

1 Answer 1

1

Which way to chose depends on the circumstances and should be part of the so called contract as in the "design by contract".

The mentioned design approach uses a metaphory saying that a function fullfills its contract. If a caller passes certain arguments, the function is obliged to do and to return exactly what is specified in that contract.

If the caller does not pass values according to the contract, then it's not the function's fault to return values unexpected by the caller or to fail in any way (of course, it must not hide any problems).

When creating software, one of the tasks is to select the right "contract". The two approaches corresponding with your question can be summarized:

1) The contract says: do your best. This is the usual way. The function is smaller, faster and more general, because it may be usable for cases not planned in advance. It takes the full advantage of Python's duck typing.

2) The contract says: take no risks, be defensive, validate inputs etc., because there are good reasons to do so.

The good coding practice is simply: know your function's contract, code accordingly, write (at least) the docstring accordingly.

Only with the knowledge of the contract you can be confident you've done a good programming job. (this icludes not worrying about possible "improvements")

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.