Skip to content

Commit

Permalink
Merge pull request Pyomo#3159 from jsiirola/config-domain
Browse files Browse the repository at this point in the history
Support config domains with either method or attribute domain_name
  • Loading branch information
blnicho authored Feb 22, 2024
2 parents 0b4ea7d + 41d8197 commit a4dc0c2
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
6 changes: 5 additions & 1 deletion pyomo/common/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -1134,7 +1134,11 @@ def _domain_name(domain):
if domain is None:
return ""
elif hasattr(domain, 'domain_name'):
return domain.domain_name()
dn = domain.domain_name
if hasattr(dn, '__call__'):
return dn()
else:
return dn
elif domain.__class__ is type:
return domain.__name__
elif inspect.isfunction(domain):
Expand Down
35 changes: 35 additions & 0 deletions pyomo/common/tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3265,6 +3265,41 @@ def __init__(
OUT.getvalue().replace('null', 'None'),
)

def test_domain_name(self):
cfg = ConfigDict()

cfg.declare('none', ConfigValue())
self.assertEqual(cfg.get('none').domain_name(), '')

def fcn(val):
return val

cfg.declare('fcn', ConfigValue(domain=fcn))
self.assertEqual(cfg.get('fcn').domain_name(), 'fcn')

fcn.domain_name = 'custom fcn'
self.assertEqual(cfg.get('fcn').domain_name(), 'custom fcn')

class functor:
def __call__(self, val):
return val

cfg.declare('functor', ConfigValue(domain=functor()))
self.assertEqual(cfg.get('functor').domain_name(), 'functor')

class cfunctor:
def __call__(self, val):
return val

def domain_name(self):
return 'custom functor'

cfg.declare('cfunctor', ConfigValue(domain=cfunctor()))
self.assertEqual(cfg.get('cfunctor').domain_name(), 'custom functor')

cfg.declare('type', ConfigValue(domain=int))
self.assertEqual(cfg.get('type').domain_name(), 'int')


if __name__ == "__main__":
unittest.main()

0 comments on commit a4dc0c2

Please sign in to comment.