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

一笑奈何 提交于 2019-11-26 23:13:29

问题


I need to determine if a given Python variable is an instance of native type: str, int, float, bool, list, dict and so on. Is there elegant way to doing it?

Or is this the only way:

if myvar in (str, int, float, bool):
    # do something

回答1:


The best way to achieve this is to collect the types in a list of tuple called primitiveTypes and:

if isinstance(myvar, primitiveTypes): ...

The types module contains collections of all important types which can help to build the list/tuple.

Works since Python 2.2




回答2:


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).




回答3:


Not that I know why you would want to do it, as there isn't any "simple" types in Python, it's all objects. But this works:

type(theobject).__name__ in dir(__builtins__)

But explicitly listing the types is probably better as it's clearer. Or even better: Changing the application so you don't need to know the difference.

Update: The problem that needs solving is how to make a serializer for objects, even those built-in. The best way to do this is not to make a big phat serializer that treats builtins differently, but to look up serializers based on type.

Something like this:

def IntSerializer(theint):
    return str(theint)

def StringSerializer(thestring):
    return repr(thestring)

def MyOwnSerializer(value):
    return "whatever"

serializers = {
    int: IntSerializer,
    str: StringSerializer,
    mymodel.myclass: MyOwnSerializer,
}

def serialize(ob):
    try:
        return ob.serialize() #For objects that know they need to be serialized
    except AttributeError:
        # Look up the serializer amongst the serializer based on type.
        # Default to using "repr" (works for most builtins).
        return serializers.get(type(ob), repr)(ob)

This way you can easily add new serializers, and the code is easy to maintain and clear, as each type has its own serializer. Notice how the fact that some types are builtin became completely irrelevant. :)




回答4:


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.




回答5:


What is a "native type" in Python? Please don't base your code on types, use Duck Typing.




回答6:


Built in type function may be helpful:

>>> a = 5
>>> type(a)
<type 'int'>



回答7:


you can access all these types by types module:

`builtin_types = [ i for i in  types.__dict__.values() if isinstance(i, type)]`

as a reminder, import module types first

def isBuiltinTypes(var):
    return type(var) in [i for i in  types.__dict__.values() if isinstance(i, type)] and not isinstance(var, types.InstanceType)



回答8:


building off of S.Lott's answer you should have something like this:


from simplejson import JSONEncoder

class JSONEncodeAll(JSONEncoder):
  def default(self, obj):
    try:
      return JSONEncoder.default(self, obj)
    except TypeError:
      ## optionally
      # try:
      #   # you'd have to add this per object, but if an object wants to do something
      #   # special then it can do whatever it wants
      #   return obj.__json__()
      # except AttributeError:
      ##

      # ...do whatever you are doing now...
      # (which should be creating an object simplejson understands)

to use:


>>> json = JSONEncodeAll()

>>> json.encode(myObject)
# whatever myObject looks like when it passes through your serialization code

these calls will use your special class and if simplejson can take care of the object it will. Otherwise your catchall functionality will be triggered, and possibly (depending if you use the optional part) an object can define it's own serialization




回答9:


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.



来源:https://stackoverflow.com/questions/1322068/determine-if-python-variable-is-an-instance-of-a-built-in-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!