Python and SWIG: local variable ‘_mod’ referenced before assignment

I was doing some stuff that requires importing C++ libraries to use in Python, and that error came up.

I’m using Stackless, so I first thought that was the case. Eventually it turned out to be related to the build configuration of the program I was compiling, FIFE.

The thing here is, SWIG generated a wrapper for that library that had a bad. It was at the very top of the wrapper file (

8  from sys import version_info
9  if version_info >= (2,6,0):
10     def swig_import_helper():
11         from os.path import dirname
12         import imp
13         fp = None
14         try:
15             fp, pathname, description = imp.find_module('_fife', [dirname(__file__)])
16         except ImportError:
17             import _fife
18             return _fife
19         if fp is not None:
20             try:
21                 _mod = imp.load_module('_fife', fp, pathname, description)
22             finally:
23                 fp.close()
24                 return _mod
25     _fife = swig_import_helper()
26     del swig_import_helper
27 else:
28     import _fife
29 del version_info

The bad thing here is that there’s no “except:” where it should be. When I added one on line 22, it caught an exception. Technically, the exception should be passed to a higher-level “try:” (on line 14). However:

1. “finally:” is executed in all cases, exception or no exception.
2. The upper-level “try:” doesn’t have a default exception handler.

I didn’t dig deeper into this, because I have no time at the moment.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: