📄 objutils.py
字号:
#----------------------------------------------------------------------------
# Name: objutils.py
# Purpose: Object Utilities
#
# Author: Alan Mullendore
#
# Created: 5/10/05
# CVS-ID: $Id: objutils.py,v 1.5 2006/04/20 06:25:51 RD Exp $
# Copyright: (c) 2004-2005 ActiveGrid, Inc.
# License: wxWindows License
#----------------------------------------------------------------------------
import logging
import traceback
import sys
import os
import __builtin__
import types
import activegrid.util.utillang as utillang
import activegrid.util.datetimeparser as datetimeparser
from types import *
from activegrid.util.lang import *
FUNCTION_HAS_ATTR = '_hasAttr'
FUNCTION_GET_ATTR = '_getAttr'
FUNCTION_SET_ATTR = '_setAttr'
FUNCTION_DEL_ATTR = '_delAttr'
def hasRawAttr(obj, name):
if obj == None:
return False
if name != FUNCTION_HAS_ATTR and hasattr(obj, FUNCTION_HAS_ATTR):
return obj._hasAttr(name)
return obj.__dict__.has_key(name)
def getRawAttr(obj, name):
if name != FUNCTION_GET_ATTR and hasattr(obj, FUNCTION_GET_ATTR):
return obj._getAttr(name)
return obj.__dict__.get(name)
def setRawAttr(obj, name, value):
if name != FUNCTION_SET_ATTR and hasattr(obj, FUNCTION_SET_ATTR):
obj._setAttr(name, value)
else:
obj.__dict__[name] = value
def delRawAttr(obj, name):
if name != FUNCTION_DEL_ATTR and hasattr(obj, FUNCTION_DEL_ATTR):
obj._delAttr(name)
else:
del obj.__dict__[name]
def getStaticAttr(obj, attr):
if (isinstance(obj, types.TypeType)):
classDesc = obj
else:
classDesc = obj.__class__
if (hasattr(classDesc, attr)):
return getattr(classDesc, attr)
return None
def setStaticAttr(obj, attr, value):
if (isinstance(obj, types.TypeType)):
classDesc = obj
else:
classDesc = obj.__class__
setattr(classDesc, attr, value)
def hasAttrFast(obj, name):
if hasRawAttr(obj, name):
return True
if hasattr(obj, '_complexType'):
complexType=obj._complexType
element=complexType.findElement(name)
if element:
return True
if hasattr(obj, name):
return True
return False
def moduleForName(moduleName):
module = None
pathList = moduleName.split('.')
if (len(moduleName) > 0):
module = __import__(moduleName)
for name in pathList[1:]:
if (name in module.__dict__):
module = module.__dict__[name]
else:
module = None
break
return module
def typeForName(typeName):
i = typeName.rfind('.')
if (i >= 0):
module = moduleForName(typeName[:i])
if (module != None):
name = typeName[i+1:]
if (name in module.__dict__):
return module.__dict__[name]
elif __builtin__.__dict__.has_key(typeName):
return __builtin__.__dict__[typeName]
return None
def functionForName(functionName):
ftype = typeForName(functionName)
if (isinstance(ftype, (types.FunctionType, types.MethodType, types.BuiltinFunctionType, types.BuiltinMethodType))):
return ftype
return None
def classForName(className):
ctype = typeForName(className)
if (isinstance(ctype, (types.ClassType, types.TypeType))):
return ctype
return None
def newInstance(className, objargs=None):
"dynamically create an object based on the className and return it."
if not isinstance(objargs, list):
objargs = [objargs]
if className == "None":
return None
elif className == "bool":
if ((len(objargs) < 1) or (objargs[0].lower() == "false") or (not objargs[0])):
return False
return True
if className == "str" or className == "unicode": # don't strip: blanks are significant
if len(objargs) > 0:
try:
return utillang.unescape(objargs[0]).encode()
except:
return "?"
else:
return ""
if className == "date":
return datetimeparser.parse(objargs[0], asdate=True)
if className == "datetime":
return datetimeparser.parse(objargs[0])
if className == "time":
return datetimeparser.parse(objargs[0], astime=True)
classtype = classForName(className)
if (classtype == None):
raise Exception("Could not find class %s" % className)
if (len(objargs) > 0):
return classtype(*objargs)
else:
return classtype()
def getClassProperty(classType, propertyName):
return getattr(classType, propertyName)
def toDiffableRepr(value, maxLevel=None):
if (value == None):
return "None"
if (maxLevel == None):
maxLevel = 8
maxLevel -= 1
if (maxLevel < 0):
return typeToString(value, PRINT_OBJ_DIFFABLE)
## if ((exclude != None) and not isinstance(value, (basestring, int))):
## for v in exclude:
## if (v is value):
## return "<recursive reference>"
## exclude.append(value)
## elif (isinstance(value, ObjectType) and hasattr(value, "__dict__")):
## if (exclude == None):
## exclude = []
## s = "%s(%s)" % (type(value), toDiffableString(value.__dict__, exclude))
if (not isinstance(value, (BooleanType, ClassType, ComplexType, DictType, DictionaryType,
FloatType, IntType, ListType, LongType, StringType, TupleType,
UnicodeType, BufferType, BuiltinFunctionType, BuiltinMethodType,
CodeType, FrameType, FunctionType, GeneratorType, InstanceType,
LambdaType, MethodType, ModuleType, SliceType, TracebackType,
TypeType, XRangeType))):
if (hasattr(value, "_toDiffableString")):
s = value._toDiffableString(maxLevel)
elif (hasattr(value, "__str__")):
s = str(value)
elif (hasattr(value, "__dict__")):
s = "%s(%s)" % (type(value), toDiffableString(value.__dict__, maxLevel))
else:
s = str(type(value))
ix2 = s.find(" object at 0x")
if (ix2 > 0):
ix = s.rfind(".")
if (ix > 0):
s = "<class %s>" %s[ix+1:ix2]
elif (isinstance(value, bool)):
if (value):
return "True"
else:
return "False"
elif (isinstance(value, (tuple, list))):
items = []
for v in value:
if (isinstance(v, basestring)):
if (v.find("'") >= 0):
items.append('"%s"' % v)
else:
items.append("'%s'" % v)
else:
items.append(toDiffableString(v, maxLevel))
s = "[" + ", ".join(items) + "]"
elif (isinstance(value, dict)):
items = []
for key, val in value.iteritems():
if (isinstance(val, UnicodeType)):
items.append("'%s': u'%s'" % (key, toDiffableString(val, maxLevel)))
elif (isinstance(val, basestring)):
items.append("'%s': '%s'" % (key, toDiffableString(val, maxLevel)))
else:
items.append("'%s': %s" % (key, toDiffableString(val, maxLevel)))
s = "{" + ", ".join(items) + "}"
else:
s = str(value)
return s
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -