Imported module goes out of scope (unbound local error)
Question: I am getting a strange "unbound local" error in a python package that seems to
defy all logic. I can't get a MWE to reproduce it, but will try to explain
succinctly and hope that someone might be able to offer some explanation of
what is going on.

For the sake of this example `module` is a package I developed, and `Model` is
a class within `module`. The definition of the `Model` class (model.py) looks
like:

    
    
    import module
    
    class Model:
        def __init__(self):
            print module
    
        def run(self):
            print module
    

Now, when I instantiate a `Model` in a script like this:

    
    
    from model import Model
    m = Model()
    m.run()
    

`module` prints successfully within the `__init__`, but I get an unbound local
error within the `run` function.

I attempted to diagnose this with pdb, which is where things got really weird,
because if I add a pdb trace immediately prior to the `print module` line in
the `run()` function, then I can successfully run `print module` without an
unbound local error, but if I step to the next line then it throws the error.
How can `module` be in the scope of `__init__()`, and in the scope of pdb, but
not in the scope of `run()`?

I know this is not ideal since there is no MWE, but I cannot seem to reproduce
this outside the context of the full code. I am hoping that someone will have
an idea of what might possibly be going on and suggest some strategies to
debug further.


Answer: Apparently you have a local variable named `module` somewhere in the function
`run`. For example, the following code will throw `UnboundLocalError`

    
    
    import sys
    
    def run():
         print sys
         sys = None
    run()
    

Here `sys = None` introduces a local name that shadows the imported `sys`
inside `run` and at the time `print` invoked it is not yet defined, hence the
error. To use the imported module inside `run` you have to find and rename the
local variable. More info on python scoping rules is
[here](https://docs.python.org/2/reference/executionmodel.html)

