Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Passing Solver explicitly causes UnboundLocalError #355

Open
DRMacIver opened this issue Jun 28, 2023 · 0 comments
Open

Passing Solver explicitly causes UnboundLocalError #355

DRMacIver opened this issue Jun 28, 2023 · 0 comments

Comments

@DRMacIver
Copy link

Describe the bug

I accidentally wrote the following (incorrect - the parameter should be solver_name) code:

import mip

model = mip.Model(sense=mip.MINIMIZE, solver=mip.CBC)

This fails with the following rather surprising error:

Traceback (most recent call last):
  File "/Users/drmaciver/Projects/sat-sampling/check_mip.py", line 3, in <module>
    model = mip.Model(sense=mip.MINIMIZE, solver=mip.CBC)
  File "/Users/drmaciver/Projects/sat-sampling/.venv/lib/python3.10/site-packages/mip/model.py", line 104, in __init__
    self.constrs = mip.ConstrList(self)
UnboundLocalError: local variable 'mip' referenced before assignment

The reason for this is that the if not solver path in model.py's Model.__init__ includes various imports that look like e.g. import mip.gurobi. Because of the way Python imports work, this means that mip is now a local variable shadowing the global import mip. In paths where that import statement has not been run (i.e. when a solver argument is explicitly passed) attempts to use mip results in this UnboundLocalError

Expected behavior

As mentioned this is incorrect code, so it's reasonable to raise an error here, although the specific error raised is quite confusing (probably a TypeError would be appropriate, but if I'd been running a static checker it would have caught it).

The more important problem is that correct code using this parameter would also fail in an identical way - currently the solver parameter cannot be used at all, because any attempt to use it will trigger this bug.

This should be an easy enough fix (adding an unconditional import mip after the if block will do it for example).

Desktop (please complete the following information):

Tested on OSX, 3.10.11 (this shouldn't matter), with mip 1.15.0 (latest version right now).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant