If I have a class such as below (only with many more properties), is there are clean way to note which fields are required before calling a particular method?
class Example():
def __init__(self):
pass
@property
"""Have to use property methods to have docstrings..."""
def prop1(self):
return self._prop1
@prop1.setter
def task(self, value):
# validation logic..
self._prop1 = value
def method(self):
# check all required properties have been added
I could write an array by hand of all required propeties and loop through them in a method, but I was wondering if there is a cleaner way for example by implementing a @requiredProperty descriptor.
The class is used to generate a POST request for a web API. The request has 25+ parameters, some of which are required and some optional.
Rather than on the method calling the request having to loop through an array such as:
required_props = ['prop1','prop2',....]
I was hoping there was a way in Python of adding a required decorator to properties so I wouldn’t have to keep track by hand. E.g.
@property, @required
def prop1(self):
return self._prop1
This should work the same way as in any OO language: A required property must be set during construction time. Calling the objects methods must never leave the object in a “bad” state, so that
methodcan be called on any constructed object.If the above doesn’t hold true, you should think about refactoring your code.
Of course it is always possible to alter a python object to not be valid anymore by poking around in its guts. You don’t do that unless you have a good reason. Don’t bother checking for this, as your program should just blow up in your face whenever you do something stupid so you learn and stop.