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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1322068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:57:20  来源:igfitidea点击:

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

pythonvariablesinstance

提问by Aleksandr Motsjonov

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

我需要确定给定的 Python 变量是否是本机类型的实例:str, int, float, bool, list,dict等等。有没有优雅的方法来做到这一点?

Or is this the only way:

或者这是唯一的方法:

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

采纳答案by Aaron Digulla

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

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

if isinstance(myvar, primitiveTypes): ...

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

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

Works since Python 2.2

从 Python 2.2 开始工作

回答by glarrain

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/givenbuilt-in type" but of a.

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

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

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

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

Warning: if objis 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).

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

回答by Lennart Regebro

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:

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

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.

更新:需要解决的问题是如何为对象(甚至是内置对象)制作序列化程序。最好的方法不是制作一个大的 phat 序列化器来区别对待内置函数,而是根据类型查找序列化器。

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

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

回答by S.Lott

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

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

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.

这比尝试猜测您的 JSON 实现处理哪些类型更可靠。

回答by S.Lott

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

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

回答by jacoolee

you can access all these types by typesmodule:

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

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

as a reminder, import module typesfirst

作为提醒,导入模块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)

回答by asterio gonzalez

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.

当 value 是一个模块并且value.__class__.__module__ == '__builtin__'会失败时,此修复。

回答by Terence Honles

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

基于 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)

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

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

回答by kolistivra

Built in type function may be helpful:

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

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