确定Python变量是否是内置类型的实例

时间:2009-08-24 12:27:22

标签: python variables instance

我需要确定给定的Python变量是否是本机类型的实例:strintfloatboollist,{ {1}}等等。这样做有优雅的方式吗?

或者这是唯一的方法:

dict

10 个答案:

答案 0 :(得分:14)

实现此目的的最佳方法是在名为primitiveTypes的元组列表中收集类型,并且:

if isinstance(myvar, primitiveTypes): ...

types module包含可以帮助构建列表/元组的所有重要类型的集合。

Works since Python 2.2

答案 1 :(得分:8)

不是我知道你为什么要这样做,因为Python中没有任何“简单”类型,它是所有对象。但这有效:

type(theobject).__name__ in dir(__builtins__)

但明确列出类型可能更好,因为它更清楚。甚至更好:更改应用程序,这样您就不需要知道差异了。

更新:需要解决的问题是如何为对象创建序列化程序,甚至是内置的对象。实现这一目标的最佳方法不是制作一个以不同方式处理内置函数的大型phat序列化程序,而是根据类型查找序列化程序。

这样的事情:

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)

通过这种方式,您可以轻松添加新的序列化程序,并且代码易于维护和清除,因为每种类型都有自己的序列化程序。注意一些类型内置的事实是如何完全无关紧要的。 :)

答案 2 :(得分:8)

这是一个老问题,但似乎没有一个答案实际上回答了具体问题:“(操作方法)确定Python变量是否是内置类型的实例”。请注意,它不是“特定/给定内置类型”,而是 a

确定给定对象是否为内置类型/类的实例的正确方法是检查对象的类型是否恰好在模块{{1}中定义}。

__builtin__

警告:如果def is_builtin_class_instance(obj): return obj.__class__.__module__ == '__builtin__' 是一个类而不是一个实例,无论该类是否内置,都会返回True,因为类也是一个对象,{{1}的一个实例}(即objtype)。

答案 3 :(得分:7)

您似乎对确保simplejson将处理您的类型感兴趣。

琐碎地完成了这项工作
try:
    json.dumps( object )
except TypeError:
    print "Can't convert", object

比猜测JSON实现处理哪些类型更可靠。

答案 4 :(得分:2)

Python中的“本机类型”是什么?请不要将代码基于类型,请使用Duck Typing

答案 5 :(得分:1)

内置类型功能可能会有所帮助:

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

答案 6 :(得分:1)

您可以通过types模块访问所有这些类型:

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

作为提醒,首先导入模块types

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

答案 7 :(得分:0)

建立S.Lott的回答你应该有这样的事情:


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)

使用:


>>> json = JSONEncodeAll()

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

这些调用将使用您的特殊类,如果simplejson可以处理它将使用的对象。否则,您的catchall功能将被触发,并且可能(取决于您是否使用可选部分)对象可以定义它自己的序列化

答案 8 :(得分:0)

对我来说,最好的选择是:

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

当值为模块并且value.__class__.__module__ == '__builtin__'将失败时,此修复。

答案 9 :(得分:0)

现在是 2020 年,我使用的是 python 3.7,现有的答案都不适合我。取而代之的是builtins module。方法如下:

import builtins
type(your_object).__name__ in dir(builtins)