I am trying to stick to Google's styleguide to strive for consistency from the beginning.
I am currently creating a module and within this module I have a class. I want to provide some sensible default values for different standard use cases. However, I want to give the user the flexibility to override any of the defaults. What I am currently doing is I provide a module scoped "constant" dictionary with the default values (for the different use cases) and in my class I give the parameters in the constructor precedence over the defaults.
Finally, I want to make sure that we end with valid values for the parameters.
That's what I have done:
MY_DEFAULTS = {"use_case_1": {"x": 1, "y": 2},
"use_case_2": {"x": 4, "y": 3}}
class MyClass:
def __init__(self, use_case = None, x = None, y = None):
self.x = x
self.y = y
if use_case:
if not self.x:
self.x = MY_DEFAULTS[use_case]["x"]
if not self.y:
self.y = MY_DEFAULTS[use_case]["y"]
assert self.x, "no valid values for 'x' provided"
assert self.y, "no valid values for 'y' provided"
def __str__(self):
return "(%s, %s)" % (self.x, self.y)
print(MyClass()) # AssertionError: no valid values for 'x' provided
print(MyClass("use_case_1")) # (1, 2)
print(MyClass("use_case_2", y = 10) # (4, 10)
Questions
- While technically working, I was wondering whether this is the most pythonic way of doing it?
- With more and more default values for my class the code becomes very repetitive, what could I do to simplify that?
assertseems also for me not the best option at it is rather a debugging statement than a validation check. I was toying with the@propertydecorator, where I would raise an Exception in case there are invalid parameters, but with the current pattern I want to allowxandyfor a short moment to be nottruthyto implement the precedence properly (that is I only want to check thetruthinessat the end of the constructor. Any hints on that?