Gurobi environment object. Note that environments play a much smaller role in the Python interface than they do in other Gurobi language APIs, mainly because the Python interface has a default environment. Unless you explicitly pass your own environment to routines that require an environment, the default environment will be used.
The primary situations where you will want to use your own environment are:
- When you are using a Gurobi Compute Server and want to choose the server from within your program.
- When you need control over garbage collection of your environment. The Gurobi Python interface maintains a reference to the default environment, so by default it will never be garbage collected. By creating your own environment, you can control exactly when your program releases any licensing tokens or Compute Servers it is using.
- When you are using concurrent environments in one of the concurrent optimizers.
It is good practice to use the with keyword when dealing with environment (and model) objects. That way the resources tied to these objects are properly released even if an exception is raised at some point. The following example illustrates two typical use patterns.
import gurobipy as gp with gp.Env("gurobi.log") as env, gp.Model(env=env) as model: # Populate model object here... m.optimize() with gp.Env(empty=True) as env: env.setParam("ComputeServer", "myserver1:32123") env.setParam("ServerPassword", "pass") env.start() with gp.Model(env=env) as model: # Populate model object here... model.optimize()
Note that you can manually remove the reference to the default environment by calling disposeDefaultEnv. After calling this, and after all models built within the default environment are garbage collected, the default environment will be garbage collected as well. A new default environment will be created automatically if you call a routine that needs one.