Skip to content

Type utilities.value and utilities.valueOrDefault #825

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion pulp/pulp.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@
import warnings
import math
from time import time
from typing import Any, Literal
from typing import Any, Literal, TypeAlias, Union

from .apis import LpSolverDefault, PULP_CBC_CMD
from .apis.core import clock
Expand All @@ -141,6 +141,12 @@

log = logging.getLogger(__name__)

LptNumber: TypeAlias = Union[int, float]
LptItem: TypeAlias = Union[LptNumber, "LpVariable"]
LptExpr: TypeAlias = Union[LptItem, "LpAffineExpression"]
LptConstExpr: TypeAlias = Union[LptNumber, "LpAffineExpression"]
LptExprConstraint: TypeAlias = Union[LptExpr, "LpConstraint"]

try:
import ujson as json # type: ignore[import-untyped]
except ImportError:
Expand Down
26 changes: 22 additions & 4 deletions pulp/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
import itertools
from itertools import combinations as combination
from itertools import permutations as permutation
from typing import Any, overload, TYPE_CHECKING

if TYPE_CHECKING:
from pulp.pulp import LptNumber, LptExpr


def resource_clock():
Expand All @@ -16,19 +20,33 @@ def isNumber(x):
return isinstance(x, (int, float))


def value(x):
@overload
def value(x: None) -> None: ...


@overload
def value(x: int) -> int: ...


@overload
def value(x: float) -> float: ...


def value(x: LptExpr | None) -> LptNumber | None:
"""Returns the value of the variable/expression x, or x if it is a number"""
if isNumber(x):
if x is None:
return None
elif isinstance(x, (int, float)):
return x
else:
return x.value()


def valueOrDefault(x):
def valueOrDefault(x: LptExpr) -> LptNumber:
"""Returns the value of the variable/expression x, or x if it is a number
Variable without value (None) are affected a possible value (within their
bounds)."""
if isNumber(x):
if isinstance(x, (int, float)):
return x
else:
return x.valueOrDefault()
Expand Down
Loading