I am currently working on implementing a Contract and lots of specialized child classes of this. For a lot of the parameters a default value does not make sense.
How do I enforce that parameter values must be provided to the constructor?
Example
import param
class Contract(param.Parameterized):
currency = param.String(allow_None=False)
amount = param.Number(allow_None=False)
# I would like this to raise an exception as the currency and amount is not provided
Contract()
I would like to avoid having to write a custom __init__ method for each Contract child. I’m looking for something like an allow_default, mandatory or require_value_on_init argument to my Parameters.
Something like the below would be a workaround. But I think something is missing from the api of Parameter?
import param
class Contract(param.Parameterized):
currency = param.String(allow_None=False)
amount = param.Number(allow_None=False)
def __init__(self, **kwargs):
for parameter in self.param.params().values():
if not parameter.allow_None and not parameter.name in kwargs:
raise ValueError(f"The parameter '{parameter.name}' was not provided!")
Contract(currency="EUR", amount=100)
# I would like this to raise an exception if currency or amount is not provided
Contract()
$ python 'scripts\specify_value.py'
> c:\repos\private\support\scripts\specify_value.py(9)__init__()
-> for parameter in self.param.params().values():
(Pdb) c
> c:\repos\private\support\scripts\specify_value.py(9)__init__()
-> for parameter in self.param.params().values():
(Pdb) c
Traceback (most recent call last):
File "C:\repos\private\support\scripts\specify_value.py", line 14, in <module>
Contract(currency="EUR", amount=100)
File "C:\repos\private\support\scripts\specify_value.py", line 9, in __init__
for parameter in self.param.params().values():
ValueError: The parameter 'currency' was not provided!