I have an instance of decimal.Decimal that comes from a SQLAlchemy query. Since I need to serialize an object, I created a JSON serializer to work with Decimal :
import decimal class AlchemyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, decimal.Decimal): return str(obj) return json.JSONEncoder.default(self, obj)
It is unfortunate that isinstance(obj, decimal.Decimal) does not return True for the instance, though (using pdb in the default method above):
obj.__class__ # => <class 'decimal.Decimal'> blah = decimal.Decimal() blah.__class__ # => <class 'decimal.Decimal'> isinstance(obj, decimal.Decimal) # => False isinstance(blah, decimal.Decimal) # => True isinstance(obj, obj.__class__) # => True
I checked that the module referenced by both instances is the same module:
import inspect inspect.getfile(obj.__class__)
I would love to understand why this does not work!
EDIT
It turns out that the problem only occurs when working in the AppEngine environment dev_appserver.py . Plain:
isinstance(db.session.execute('SELECT amount FROM model LIMIT 1').fetchone()[0], decimal.Decimal)
returns False when executing a request through AppEngine dev_appserver and True when starting from the console.
source share