Python Attribute Examples

Consider the case where you have a Gurobi model <span>$</span>m<span>$</span>. You can retrieve the number of variables in the model by querying the NumVars model attribute:

  print(m.numVars)
(Note that attribute capitalization doesn't matter in the Python interface, so you could also query <span>$</span>m.NumVars<span>$</span> or <span>$</span>m.numvars<span>$</span>).

If you've performed optimization on the model, the optimal objective value can be obtained by querying the ObjVal model attribute:

  print(m.objVal)

If you'd like to query the value that a variable takes in the computed solution, you can query the X attribute for the corresponding variable object:

  for v in m.getVars():
    print(v.x)
You can also query the value of <span>$</span>X<span>$</span> for multiple variables in a single getAttr call on the model <span>$</span>m<span>$</span>:
  print(m.getAttr(GRB.Attr.x, m.getVars()))

For each attribute query method, there's an analogous <span>$</span>set<span>$</span> routine. To set the upper bound of a variable, for example:

  v = m.getVars()[0]
  v.ub = 0
(In this example, we've set the upper bound for the first variable in the model to 0).

Try Gurobi for Free

Choose the evaluation license that fits you best, and start working with our Expert Team for technical guidance and support.

Evaluation License
Get a free, full-featured license of the Gurobi Optimizer to experience the performance, support, benchmarking and tuning services we provide as part of our product offering.
Academic License
Gurobi supports the teaching and use of optimization within academic institutions. We offer free, full-featured copies of Gurobi for use in class, and for research.
Cloud Trial

Request free trial hours, so you can see how quickly and easily a model can be solved on the cloud.

Search