Ali SAID OMAR Ali SAID OMAR - 2 months ago 11
Python Question

Proper way to check type when object might be an object() instance

I'm looking for the proper way to check a type of object that might be an instance of object() now i'm doing this:

def _default_json_encoder(obj):
""" Default encoder, encountered must have to_dict
method to be serialized. """
if hasattr(obj, "to_dict"):
return obj.to_dict()
else:
# object() is used in the base code to be evaluated as True
if type(obj) == type(object()):
return {}
raise TypeError(
'Object of type %s with value of '
'%s is not JSON serializable'
% (type(obj), repr(obj))
)


but

if type(obj) == type(object()):
return {}


is not recommended, unfortunately

if isinstance(obj, object):
return {}


won't work because all object will be evaluated as True.

So
type(obj) == type(object())
is the only way ?

Answer

If you really have instances of object() in your data structure, then you'd use:

type(obj) is object

to test for direct instances (classes are typically singletons).

However, I'd rethink my data structure, and either use another primitive value (like True), a dedicated singleton, or a dedicated class.

A dedicated singleton could be:

sentinel = object()

then test for that sentinel:

if obj is sentinel:
    return {}
Comments