我需要确定给定的Python变量是原生类型的实例的实例:str
,int
,float
,bool
,list
,dict
等。有没有优雅的方式来做到这一点?确定是否Python变量是一个内置式
或者这是唯一的方法:
if myvar in (str, int, float, bool):
# do something
我需要确定给定的Python变量是原生类型的实例的实例:str
,int
,float
,bool
,list
,dict
等。有没有优雅的方式来做到这一点?确定是否Python变量是一个内置式
或者这是唯一的方法:
if myvar in (str, int, float, bool):
# do something
实现这一目标的最好办法是收集类型称为primitiveTypes
和元组的列表:
if isinstance(myvar, primitiveTypes): ...
的types
module包含了所有重要的类型的集合,可以帮助建立列表/元组。
thx。它可能比我最初写的更优雅。 – 2009-08-24 12:52:55
使用“类型”中的类型与直接使用更直接的名称(int,str,float,...)没有区别! – u0b34a0f6ae 2009-08-24 13:07:20
是的,这就是类型的工作原理。但它使你的意图更加清晰,如果你使用预定义的集合(StringTypes),你将获得Python版本之间的附加可移植性。 – 2009-08-24 13:37:34
内置式功能可能会有所帮助:
>>> a = 5
>>> type(a)
<type 'int'>
不是我知道你为什么想这样做,因为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)
这样,您就可以轻松地添加新的串行器,代码易于维护和明确的,因为每个类型都有其自己的序列。注意一些类型是内置的事实如何变得完全不相关。 :)
你似乎是有意确保在simplejson将处理您的类型。这是由
try:
json.dumps(object)
except TypeError:
print "Can't convert", object
这是不是试图去猜测你的JSON实现处理哪些类型的更可靠的平凡完成。
这是更pythonic因为如果对象可以倾倒(也许simplejson增加更多的支持),那么它将首先使用,然后在除了你应该调用你的catchall功能。 +1 – 2009-08-24 22:28:13
建设关美国洛特的回答,你应该有这样的事情:
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。
到的正确方法确定给定的目的是实例的BUIL-在类型/类别是检查对象的类型发生在模块__builtin__
中被定义。
def is_builtin_class_instance(obj):
return obj.__class__.__module__ == '__builtin__'
警告:如果obj
是一类,而不是一个实例,不管这个类是内置的或没有,返回True因为一个类也是一个对象,而type
实例(即AnyClass.__class__
是type
)。
您可以通过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)
对我来说,最好的选择是:
allowed_modules = set(['numpy'])
def isprimitive(value):
return not hasattr(value, '__dict__') or \
value.__class__.__module__ in allowed_modules
如果值为模块并且value.__class__.__module__ == '__builtin__'
将失败,则此修复。
你是什么意思的“本地”类型?你的意思是内建吗?你为什么需要知道这个? Python不是C++或Java,所以“简单”或“本地”类型之间没有区别。你想做什么? – 2009-08-24 12:30:58
是的,我想我的意思是“内建”类型。 我需要这样的对象表示,我可以在JSON序列化中使用它。 simplejson只处理这种类型。在其他情况下(当对象是“自制”类的实例时),我需要制作字典对象。 – 2009-08-24 12:43:40
你知道simplejson有一些叫做“对象解码”和“对象编码”的东西吗? – 2009-08-24 12:46:23