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

确定Python变量是否为内置类型的实例,python,variables,instance,Python,Variables,Instance,我需要确定给定的Python变量是否是本机类型的实例:str,int,float,bool,list,dict等等。有优雅的方法吗 或者这是唯一的方法: if myvar in (str, int, float, bool): # do something 内置类型函数可能有帮助: >>> a = 5 >>> type(a) <type 'int'> >a=5 >>>类型(a) Python中的“本机类型”是什么?请不要将您的代码基于类

我需要确定给定的Python变量是否是本机类型的实例:
str
int
float
bool
list
dict
等等。有优雅的方法吗

或者这是唯一的方法:

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

内置类型函数可能有帮助:

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

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

我不知道您为什么要这样做,因为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)

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)

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

实现这一点的最佳方法是收集名为
primitiveTypes
的元组列表中的类型,并:

if isinstance(myvar, primitiveTypes): ...
包含可以帮助构建列表/元组的所有重要类型的集合


您似乎对确保simplejson能够处理您的类型感兴趣。这是由一个微不足道的人完成的

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

这比猜测JSON实现所处理的类型更可靠。

基于S.Lott的答案,您应该有如下内容:

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)

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功能将被触发,并且可能(取决于您是否使用可选部分)一个对象可以定义它自己的序列化

这是一个老问题,但似乎没有一个答案真正回答了特定的问题:“(如何)确定Python变量是否是内置类型的实例”。请注意,它不是“[…]特定/给定的内置类型”,而是a

确定给定对象是否为内置类型/类实例的正确方法是检查对象的类型是否恰好在模块
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

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

警告:如果
obj
是一个类而不是实例,无论该类是否内置,都将返回True,因为类也是一个对象,
类型的实例(即
AnyClass.\uu class\uuu
类型
)。

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

`builtin_types = [ i for i in  types.__dict__.values() if isinstance(i, type)]`
作为提醒,首先导入模块
类型

def isBuiltinTypes(var):
    return type(var) in types.__dict__.values() and not isinstance(var, types.InstanceType)

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

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

当值是一个模块和
值时,此修复将失败。

现在是2020年,我使用的是python 3.7,现有的答案对我都不起作用。取而代之的是新技术。以下是方法:

导入内置项
键入(您的对象)。\uuuuu name\uuuuuuuuuuuu在目录中(内置)

您所说的“本机”类型是什么意思?你是说内置的吗?你为什么要知道这些?Python不是C++或java,所以在“简单”或“原生”类型之间没有区别。你想干什么?是的,我想我指的是“内置”类型。我需要这样的对象表示,以便在JSON序列化中使用它。simplejson仅“处理”此类类型。在其他情况下(当对象是“自制”类的实例时),我需要生成dict对象。你知道simplejson有一种叫做“对象解码”和“对象编码”的东西吗?是的,但正如我所理解的,我应该为我想要序列化的每种类编写这样的解码器。我不想这样做。@Aleksandr Motsjonov:请更新您的问题,明确表示您对simplejson默认处理的类型感兴趣。+1“更改应用程序,这样您就不需要知道差异了。”有些(非常罕见)情况需要知道,但很可能不是。谢谢,在使用“types”中的类型与直接使用更直接的名称(int、str、float等)没有什么不同!是的,类型就是这样工作的。但是它使您的意图更加清晰,如果您使用预定义的集合(StringTypes),您可以在Python版本之间获得额外的可移植性。它还稍微快一点…;)请注意,
类型
模块并没有真正提供完整的类型列表。例如,那里没有
int
。然而,有一个
buildins
模块提供了大多数内置函数,因此可以对dir(builtins)中的t执行
builtin_types=tuple(getattr(builtins,t)如果是instance(getattr(builtins,t),type))
然后使用
isinstance(value,builtin_types)
isinstance
对于内置类型的子类是true,而(bool、str、int、float、tuple、list、dict)中的
类型(值)
仅适用于内置类型的实例。这个答案指出了这个区别:这更像python,因为如果可以转储对象(比如说simplejson添加了更多支持),那么将首先使用它,然后在中使用它,除非您应该调用catchall功能+1在Python3中,该模块称为
\uuuuuuuuuuuuuuuuuuuuuuu
。在Python3.7中,该模块称为
builtins
@glarrain。您如何修改该模块以处理您提到的一般情况,即
obj
是一个类而不是一个实例?