I have a custom class like this:
import json
class Config:
def __init__(self):
self._field1 = None
self._field2 = None
@property
def field1(self):
return self._field1
@field1.setter
def field1(self, value):
self._field1 = value
@property
def field2(self):
return self._field2
@field2.setter
def field2(self, value):
self._field2 = value
def validate(self):
fields = [attribute for attribute in dir(self) if not attribute.startswith('__') and not callable(getattr(self, attribute))]
for field in fields:
if getattr(self, field) == None:
raise AttributeError("You must set all fields, " + str(field) + " is not set")
def toJSON(self):
return json.dumps(self, default=lambda o: vars(o),
sort_keys=True, indent=4)
As you can see I try to JSON serialize my class, but it will always include the _ prefix in the json (since vars will return that)
Question 1: How can I get rid of it?
Question 2: I tried to delete the _ prefixes from the class but then I will get a "Error: maximum recursion depth exceeded while calling a Python object" when calling the constructor. Why is that happening?
Later on I might add validation logic to the setters.
Also if you have any suggestions how to refactor my code, please don't keep it to yourself.