1

Before using the value of a return of a function, I want to check if the value is useable. So what I have is more or less the following:

def get_module():
  import foo
  return foo

def do_something():
  try:
    module = get_module()
  except:
    print "error"

  module.bar()

Unfortunately, it seems to me that this never raises an exception. In particular, I want to check (a) that the module was transferred correctly and (b) that the module is one of three possible modules.

I know I can check through if-statements, but I feel that exception handing is ought to be the correct way.

1
  • it never raises an exception... if foo doesn't exist. Otherwise get_module will raise ImportError (which you should catch explicitly instead of a bare except) Commented Mar 17, 2014 at 17:52

1 Answer 1

1

If foo cannot be imported, the code below will produce an ImportError exception:

def get_module():
    import foo
    return foo


def do_something():
    try:
        module = get_module()
    except ImportError:
        print "Import Error!"
        raise

    module.bar()


do_something()

Produces:

Import Error! 
Traceback (most recent call last):
    ...
import foo 
ImportError: No module named foo

Note, that you should either reraise the exception via raise in the except block, or make a return, so that you don't get an error on module.bar() line because of undefined module variable.

Hope that helps.

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

1 Comment

Ah yes. I think I start to get Python's exception handling. Thank you!

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.