I have the following class with the variables from
, to
and rate
. from
is a keyword. If I want to use it in the init method below, what's the correct way to write it?
More context: The class needs the from
variable explicitly as it's part of a json required by a POST endpoint written up by another developer in a different language. So changing the variable name is out of the question.
class ExchangeRates(JsonAware):
def __init__(self, from, to, rate):
self.from = from
self.to = to
self.rate = rate
JsonAware code:
class PropertyEquality(object):
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__)
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, ', '.join(['%s=%s' % (k, v) for (k, v) in self.__dict__.items()]))
class JsonAware(PropertyEquality):
def json(self):
return json.dumps(self, cls=GenericEncoder)
@classmethod
def from_json(cls, json):
return cls(**json)
GenericEncoder code:
class GenericEncoder(json.JSONEncoder):
def default(self, obj):
return obj.__dict__
from_
instead. - jonrsharpefrom
is used 3 times, and it's being flagged in red 3 times, don't I have to escape they keyword or something using **kwargs? - user4659009setattr(self, 'from', kwargs.get('from'))
, but then you have to pass it in via a dictionary too:rates = ExchangeRates(..., **{'from': whatever})
and can only access it viagetattr(rates, 'from')
. It's much less awkward to rename it. See e.g. stackoverflow.com/q/9746838/3001761 - jonrsharpeJsonAware
?), there are probably ways to handle parsing to and from JSON where the keys are keywords. But you definitely can't do it directly. - jonrsharpe