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

Support config domains with either method or attribute domain_name #3159

Merged
merged 1 commit into from
Feb 22, 2024
Merged
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
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()