Determine if Python variable is an instance of a built-in type

前端 未结 9 2333
难免孤独
难免孤独 2020-12-05 23:39

I need to determine if a given Python variable is an instance of native type: str, int, float, bool, list, <

相关标签:
9条回答
  • 2020-12-06 00:17

    You appear to be interested in assuring the simplejson will handle your types. This is done trivially by

    try:
        json.dumps( object )
    except TypeError:
        print "Can't convert", object
    

    Which is more reliable than trying to guess which types your JSON implementation handles.

    0 讨论(0)
  • 2020-12-06 00:17

    For me the best option is:

    allowed_modules = set(['numpy'])
    def isprimitive(value):
      return not hasattr(value, '__dict__') or \
      value.__class__.__module__ in allowed_modules
    

    This fix when value is a module and value.__class__.__module__ == '__builtin__' will fail.

    0 讨论(0)
  • 2020-12-06 00:20

    This is an old question but it seems none of the answers actually answer the specific question: "(How-to) Determine if Python variable is an instance of a built-in type". Note that it's not "[...] of a specific/given built-in type" but of a.

    The proper way to determine if a given object is an instance of a buil-in type/class is to check if the type of the object happens to be defined in the module __builtin__.

    def is_builtin_class_instance(obj):
        return obj.__class__.__module__ == '__builtin__'
    

    Warning: if obj is a class and not an instance, no matter if that class is built-in or not, True will be returned since a class is also an object, an instance of type (i.e. AnyClass.__class__ is type).

    0 讨论(0)
提交回复
热议问题