0

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 ?

5
  • 2
    Why do you think you need to test for object instances? Everything in Python 3 is an instance of (a subclass of) object. Do you have actual object() instances in your data, and if you do, why? Commented Sep 30, 2016 at 10:25
  • 1
    And the usual way to test for a class is to use isinstance(obj, class), but again, for the object class, that's everything. You can use type(obj) is object to disallow any subclasses. I'm puzzled as to why you'd need this however. Why not just use True or some dedicated class instead? Commented Sep 30, 2016 at 10:25
  • @MartijnPieters, because in some case the I have made affectation with object() then i need to repr this (instance attribute) as dict. Commented Sep 30, 2016 at 10:32
  • But why? What is the actual problem you tried to solve by using object()? Commented Sep 30, 2016 at 10:33
  • I answered in my previous comment. the need to repr an instance attribute as {}. Commented Sep 30, 2016 at 10:36

1 Answer 1

1

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 {}
Sign up to request clarification or add additional context in comments.

1 Comment

As usual nice response, Thanks !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.