0

I am a newbie to python and I have an indentation error message when I commented ('#') the two last lines of the following code :

    try:
        return get_callable(callback), {}
#   except (ImportError, AttributeError), e:
#       raise ViewDoesNotExist("Tried %s. Error was: %s" % (callback, st    r(e)))

Can anybody help ?

3
  • @Acorn : Sorry I was also editing my code. But why have I been down voted ? Commented Sep 27, 2012 at 22:59
  • A try block must be closed with a except Commented Sep 27, 2012 at 22:59
  • Here's the message : def resolve404(self): ^ IndentationError: unexpected unindent Commented Sep 27, 2012 at 23:01

3 Answers 3

5

When commenting out a try / except, place a if True: # in front of the try:

    if True: #try:
        return get_callable(callback), {}
#   except (ImportError, AttributeError), e:
#       raise ViewDoesNotExist("Tried %s. Error was: %s" % (callback, st    r(e)))

This makes for correct syntax without having to de-dent the inner block. You could also add a finally: pass block after the commented except:

    try:
        return get_callable(callback), {}
#   except (ImportError, AttributeError), e:
#       raise ViewDoesNotExist("Tried %s. Error was: %s" % (callback, st    r(e)))
    finally:
        pass

Your only other option is to comment out the try: line as well, and remove the indentation of the block:

#   try:
    return get_callable(callback), {}
#   except (ImportError, AttributeError), e:
#       raise ViewDoesNotExist("Tried %s. Error was: %s" % (callback, st    r(e)))

You cannot leave a bare try: in place without an except or finally block to complete it.

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

Comments

4

Your code is no longer syntactically valid. The except clause is a required companion of the try clause.

2 Comments

Oh ok, I know nothing from python, how can I put a 'null code' to the except clause, so it doesn't affect the running of the code ?
@user1611830 I don't know what you mean. Do you want the exception to still be caught, but do nothing on that event, or do you want the exception to propagate as if the clause weren't there?
2

If there is not another except statement, python is looking for an except statement and instead likely sees an unindented line.

So you might think, "why is this an indentation error? I'm just missing an except, which doesn't have anything to do with indents." The reason is that python "sees" an unindented line following a try: and expects it to be indented to be inside the try.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.