Update of /cvsroot/pywin32/pywin32/com/win32com/client
In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv24802/com/win32com/client
Modified Files:
CLSIDToClass.py __init__.py build.py gencache.py genpy.py
makepy.py selecttlb.py
Log Message:
Various modernizations to .py code via the py3k branch.
Index: makepy.py
===================================================================
RCS file: /cvsroot/pywin32/pywin32/com/win32com/client/makepy.py,v
retrieving revision 1.25
retrieving revision 1.26
diff -C2 -d -r1.25 -r1.26
*** makepy.py 1 Jul 2008 00:17:41 -0000 1.25
--- makepy.py 14 Nov 2008 00:22:25 -0000 1.26
***************
*** 218,223 ****
if bForDemand and file is not None:
! raise RuntimeError, "You can only perform a demand-build when the output goes to the gen_py directory"
! if type(typelibInfo)==type(()):
# Tuple
typelibCLSID, lcid, major, minor = typelibInfo
--- 218,223 ----
if bForDemand and file is not None:
! raise RuntimeError("You can only perform a demand-build when the output goes to the gen_py directory")
! if isinstance(typelibInfo, tuple):
# Tuple
typelibCLSID, lcid, major, minor = typelibInfo
***************
*** 226,230 ****
spec.FromTypelib(tlb, str(typelibCLSID))
typelibs = [(tlb, spec)]
! elif type(typelibInfo)==types.InstanceType:
if typelibInfo.dll is None:
# Version numbers not always reliable if enumerated from registry.
--- 226,230 ----
spec.FromTypelib(tlb, str(typelibCLSID))
typelibs = [(tlb, spec)]
! elif isinstance(typelibInfo, selecttlb.TypelibSpec):
if typelibInfo.dll is None:
# Version numbers not always reliable if enumerated from registry.
***************
*** 235,238 ****
--- 235,240 ----
elif hasattr(typelibInfo, "GetLibAttr"):
# A real typelib object!
+ # Could also use isinstance(typelibInfo, PyITypeLib) instead, but PyITypeLib is not directly exposed by pythoncom.
+ # pythoncom.TypeIIDs[pythoncom.IID_ITypeLib] seems to work
tla = typelibInfo.GetLibAttr()
guid = tla[0]
***************
*** 287,291 ****
fileUse.close()
os.rename(outputName + ".temp", outputName)
-
if bToGenDir:
progress.SetDescription("Importing module")
--- 289,292 ----
Index: __init__.py
===================================================================
RCS file: /cvsroot/pywin32/pywin32/com/win32com/client/__init__.py,v
retrieving revision 1.35
retrieving revision 1.36
diff -C2 -d -r1.35 -r1.36
*** __init__.py 3 Oct 2008 01:03:56 -0000 1.35
--- __init__.py 14 Nov 2008 00:22:25 -0000 1.36
***************
*** 6,18 ****
# dispatch object, the known class will be used. This contrasts
# with dynamic.Dispatch behaviour, where dynamic objects are always used.
- import __builtin__
- # For some bizarre reason, __builtins__ fails with attribute error on __dict__ here?
- NeedUnicodeConversions = not hasattr(__builtin__, "unicode")
! import dynamic, gencache, pythoncom
import sys
import pywintypes
! from types import TupleType
! from pywintypes import UnicodeType
_PyIDispatchType = pythoncom.TypeIIDs[pythoncom.IID_IDispatch]
--- 6,18 ----
# dispatch object, the known class will be used. This contrasts
# with dynamic.Dispatch behaviour, where dynamic objects are always used.
! # This can go away
! NeedUnicodeConversions = False
!
! import pythoncom
! import dynamic, gencache
import sys
import pywintypes
!
_PyIDispatchType = pythoncom.TypeIIDs[pythoncom.IID_IDispatch]
***************
*** 66,70 ****
if (Pathname is None and Class is None) or \
(Pathname is not None and Class is not None):
! raise ValueError, "You must specify a value for Pathname or Class, but not both."
if Class is not None:
--- 66,70 ----
if (Pathname is None and Class is None) or \
(Pathname is not None and Class is not None):
! raise ValueError("You must specify a value for Pathname or Class, but not both.")
if Class is not None:
***************
*** 128,136 ****
if hasattr(target, "index"): # string like
# for now, we assume makepy for this to work.
! if not ob.__class__.__dict__.has_key("CLSID"):
# Eeek - no makepy support - try and build it.
ob = gencache.EnsureDispatch(ob)
! if not ob.__class__.__dict__.has_key("CLSID"):
! raise ValueError, "Must be a makepy-able object for this to work"
clsid = ob.CLSID
# Lots of hoops to support "demand-build" - ie, generating
--- 128,136 ----
if hasattr(target, "index"): # string like
# for now, we assume makepy for this to work.
! if "CLSID" not in ob.__class__.__dict__:
# Eeek - no makepy support - try and build it.
ob = gencache.EnsureDispatch(ob)
! if "CLSID" not in ob.__class__.__dict__:
! raise ValueError("Must be a makepy-able object for this to work")
clsid = ob.CLSID
# Lots of hoops to support "demand-build" - ie, generating
***************
*** 148,153 ****
target_clsid = mod.NamesToIIDMap.get(target)
if target_clsid is None:
! raise ValueError, "The interface name '%s' does not appear in the " \
! "same library as object '%r'" % (target, ob)
mod = gencache.GetModuleForCLSID(target_clsid)
target_class = getattr(mod, target)
--- 148,153 ----
target_clsid = mod.NamesToIIDMap.get(target)
if target_clsid is None:
! raise ValueError("The interface name '%s' does not appear in the " \
! "same library as object '%r'" % (target, ob))
mod = gencache.GetModuleForCLSID(target_clsid)
target_class = getattr(mod, target)
***************
*** 155,159 ****
target_class = getattr(target_class, "default_interface", target_class)
return target_class(ob) # auto QI magic happens
! raise ValueError, "This object can not be cast"
class Constants:
--- 155,159 ----
target_class = getattr(target_class, "default_interface", target_class)
return target_class(ob) # auto QI magic happens
! raise ValueError
class Constants:
***************
*** 164,170 ****
def __getattr__(self, a):
for d in self.__dicts__:
! if d.has_key(a):
return d[a]
! raise AttributeError, a
# And create an instance.
--- 164,170 ----
def __getattr__(self, a):
for d in self.__dicts__:
! if a in d:
return d[a]
! raise AttributeError(a)
# And create an instance.
***************
*** 252,256 ****
disp_class = gencache.GetClassForProgID(str(disp_clsid))
except pythoncom.com_error:
! raise TypeError, "This COM object can not automate the makepy process - please run makepy manually for this object"
else:
disp_class = disp.__class__
--- 252,256 ----
disp_class = gencache.GetClassForProgID(str(disp_clsid))
except pythoncom.com_error:
! raise TypeError("This COM object can not automate the makepy process - please run makepy manually for this object")
else:
disp_class = disp.__class__
***************
*** 261,265 ****
events_class = getevents(clsid)
if events_class is None:
! raise ValueError, "This COM object does not support events."
result_class = new.classobj("COMEventClass", (disp_class, events_class, user_event_class), {"__setattr__" : _event_setattr_})
instance = result_class(disp._oleobj_) # This only calls the first base class __init__.
--- 261,265 ----
events_class = getevents(clsid)
if events_class is None:
! raise ValueError("This COM object does not support events.")
result_class = new.classobj("COMEventClass", (disp_class, events_class, user_event_class), {"__setattr__" : _event_setattr_})
instance = result_class(disp._oleobj_) # This only calls the first base class __init__.
***************
*** 304,308 ****
disp_class = gencache.GetClassForProgID(str(disp_clsid))
except pythoncom.com_error:
! raise TypeError, "This COM object can not automate the makepy process - please run makepy manually for this object"
else:
disp_class = disp.__class__
--- 304,308 ----
disp_class = gencache.GetClassForProgID(str(disp_clsid))
except pythoncom.com_error:
! raise TypeError("This COM object can not automate the makepy process - please run makepy manually for this object")
else:
disp_class = disp.__class__
***************
*** 314,318 ****
events_class = getevents(clsid)
if events_class is None:
! raise ValueError, "This COM object does not support events."
result_class = new.classobj("COMEventClass", (events_class, user_event_class), {})
instance = result_class(disp) # This only calls the first base class __init__.
--- 314,318 ----
events_class = getevents(clsid)
if events_class is None:
! raise ValueError("This COM object does not support events.")
result_class = new.classobj("COMEventClass", (events_class, user_event_class), {})
instance = result_class(disp) # This only calls the first base class __init__.
***************
*** 401,406 ****
struct_guid = package.RecordMap[name]
except KeyError:
! raise ValueError, "The structure '%s' is not defined in module '%s'" % (name, package)
!
return pythoncom.GetRecordFromGuids(module.CLSID, module.MajorVersion, module.MinorVersion, module.LCID, struct_guid)
--- 401,405 ----
struct_guid = package.RecordMap[name]
except KeyError:
! raise ValueError("The structure '%s' is not defined in module '%s'" % (name, package))
return pythoncom.GetRecordFromGuids(module.CLSID, module.MajorVersion, module.MinorVersion, module.LCID, struct_guid)
***************
*** 442,464 ****
return cmp(self._oleobj_, other)
! def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user,
! resultCLSID, *args):
return self._get_good_object_(
! self._oleobj_.InvokeTypes(
! dispid, 0, wFlags, retType, argTypes, *args),
! user, resultCLSID)
def __getattr__(self, attr):
args=self._prop_map_get_.get(attr)
if args is None:
! raise AttributeError, "'%s' object has no attribute '%s'" % (repr(self), attr)
return self._ApplyTypes_(*args)
def __setattr__(self, attr, value):
! if self.__dict__.has_key(attr): self.__dict__[attr] = value; return
try:
args, defArgs=self._prop_map_put_[attr]
except KeyError:
! raise AttributeError, "'%s' object has no attribute '%s'" % (repr(self), attr)
self._oleobj_.Invoke(*(args + (value,) + defArgs))
def _get_good_single_object_(self, obj, obUserName=None, resultCLSID=None):
--- 441,461 ----
return cmp(self._oleobj_, other)
! def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *args):
return self._get_good_object_(
! self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),
! user, resultCLSID)
def __getattr__(self, attr):
args=self._prop_map_get_.get(attr)
if args is None:
! raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr))
return self._ApplyTypes_(*args)
def __setattr__(self, attr, value):
! if attr in self.__dict__: self.__dict__[attr] = value; return
try:
args, defArgs=self._prop_map_put_[attr]
except KeyError:
! raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr))
self._oleobj_.Invoke(*(args + (value,) + defArgs))
def _get_good_single_object_(self, obj, obUserName=None, resultCLSID=None):
***************
*** 471,476 ****
if _PyIDispatchType==type(obj):
return Dispatch(obj, obUserName, resultCLSID, UnicodeToString=NeedUnicodeConversions)
- elif NeedUnicodeConversions and UnicodeType==type(obj):
- return str(obj)
return obj
--- 468,471 ----
***************
*** 478,482 ****
if obj is None:
return None
! elif type(obj)==TupleType:
obUserNameTuple = (obUserName,) * len(obj)
resultCLSIDTuple = (resultCLSID,) * len(obj)
--- 473,477 ----
if obj is None:
return None
! elif isinstance(obj, tuple):
obUserNameTuple = (obUserName,) * len(obj)
resultCLSIDTuple = (resultCLSID,) * len(obj)
***************
*** 495,501 ****
d=self.__dict__["_dispobj_"]
if d is not None: return getattr(d, attr)
! raise AttributeError, attr
def __setattr__(self, attr, value):
! if self.__dict__.has_key(attr): self.__dict__[attr] = value; return
try:
d=self.__dict__["_dispobj_"]
--- 490,496 ----
d=self.__dict__["_dispobj_"]
if d is not None: return getattr(d, attr)
! raise AttributeError(attr)
def __setattr__(self, attr, value):
! if attr in self.__dict__: self.__dict__[attr] = value; return
try:
d=self.__dict__["_dispobj_"]
Index: build.py
===================================================================
RCS file: /cvsroot/pywin32/pywin32/com/win32com/client/build.py,v
retrieving revision 1.32
retrieving revision 1.33
diff -C2 -d -r1.32 -r1.33
*** build.py 3 Oct 2008 01:03:56 -0000 1.32
--- build.py 14 Nov 2008 00:22:25 -0000 1.33
***************
*** 121,125 ****
else:
deleteExisting = 1 # No good to us
! if self.mapFuncs.has_key(key) or self.propMapGet.has_key(key):
newKey = "Set" + key
else:
--- 121,125 ----
else:
deleteExisting = 1 # No good to us
! if key in self.mapFuncs or key in self.propMapGet:
newKey = "Set" + key
else:
***************
*** 138,142 ****
else:
deleteExisting = 1 # No good to us
! if self.mapFuncs.has_key(key):
newKey = "Get" + key
else:
--- 138,142 ----
else:
deleteExisting = 1 # No good to us
! if key in self.mapFuncs:
newKey = "Get" + key
else:
***************
*** 257,266 ****
if typeinfo is None: return
# Loop over all methods
! for j in xrange(attr[6]):
fdesc = typeinfo.GetFuncDesc(j)
self._AddFunc_(typeinfo,fdesc,bForUser)
# Loop over all variables (ie, properties)
! for j in xrange(attr[7]):
fdesc = typeinfo.GetVarDesc(j)
self._AddVar_(typeinfo,fdesc,bForUser)
--- 257,266 ----
if typeinfo is None: return
# Loop over all methods
! for j in range(attr[6]):
fdesc = typeinfo.GetFuncDesc(j)
self._AddFunc_(typeinfo,fdesc,bForUser)
# Loop over all variables (ie, properties)
! for j in range(attr[7]):
fdesc = typeinfo.GetVarDesc(j)
self._AddVar_(typeinfo,fdesc,bForUser)
***************
*** 269,276 ****
# that have arguments, we must turn them into methods. If a method
# of the same name already exists, change the name.
! for key, item in self.propMapGet.items():
self._propMapGetCheck_(key,item)
! for key, item in self.propMapPut.items():
self._propMapPutCheck_(key,item)
--- 269,276 ----
# that have arguments, we must turn them into methods. If a method
# of the same name already exists, change the name.
! for key, item in list(self.propMapGet.items()):
self._propMapGetCheck_(key,item)
! for key, item in list(self.propMapPut.items()):
self._propMapPutCheck_(key,item)
***************
*** 316,319 ****
--- 316,320 ----
defOutArg = "pythoncom.Missing"
id = fdesc[0]
+
s = linePrefix + 'def ' + name + '(self' + BuildCallList(fdesc, names, defNamedOptArg, defNamedNotOptArg, defUnnamedArg, defOutArg) + '):'
ret.append(s)
***************
*** 330,347 ****
# Strip the default values from the arg desc
retDesc = fdesc[8][:2]
! argsDesc = tuple(map(lambda what: what[:2], fdesc[2]))
# The runtime translation of the return types is expensive, so when we know the
# return type of the function, there is no need to check the type at runtime.
# To qualify, this function must return a "simple" type, and have no byref args.
# Check if we have byrefs or anything in the args which mean we still need a translate.
! param_flags = map(lambda what: what[1], fdesc[2])
! bad_params = filter(lambda flag: flag & (pythoncom.PARAMFLAG_FOUT | pythoncom.PARAMFLAG_FRETVAL)!=0, param_flags)
s = None
if len(bad_params)==0 and len(retDesc)==2 and retDesc[1]==0:
rd = retDesc[0]
! if NoTranslateMap.has_key(rd):
s = '%s\treturn self._oleobj_.InvokeTypes(%d, LCID, %s, %s, %s%s)' % (linePrefix, id, fdesc[4], retDesc, argsDesc, _BuildArgList(fdesc, names))
elif rd in [pythoncom.VT_DISPATCH, pythoncom.VT_UNKNOWN]:
! s = '%s\tret = self._oleobj_.InvokeTypes(%d, LCID, %s, %s, %s%s)\n' % (linePrefix, id, fdesc[4], retDesc, `argsDesc`, _BuildArgList(fdesc, names))
s = s + '%s\tif ret is not None:\n' % (linePrefix,)
if rd == pythoncom.VT_UNKNOWN:
--- 331,348 ----
# Strip the default values from the arg desc
retDesc = fdesc[8][:2]
! argsDesc = tuple([what[:2] for what in fdesc[2]])
# The runtime translation of the return types is expensive, so when we know the
# return type of the function, there is no need to check the type at runtime.
# To qualify, this function must return a "simple" type, and have no byref args.
# Check if we have byrefs or anything in the args which mean we still need a translate.
! param_flags = [what[1] for what in fdesc[2]]
! bad_params = [flag for flag in param_flags if flag & (pythoncom.PARAMFLAG_FOUT | pythoncom.PARAMFLAG_FRETVAL)!=0]
s = None
if len(bad_params)==0 and len(retDesc)==2 and retDesc[1]==0:
rd = retDesc[0]
! if rd in NoTranslateMap:
s = '%s\treturn self._oleobj_.InvokeTypes(%d, LCID, %s, %s, %s%s)' % (linePrefix, id, fdesc[4], retDesc, argsDesc, _BuildArgList(fdesc, names))
elif rd in [pythoncom.VT_DISPATCH, pythoncom.VT_UNKNOWN]:
! s = '%s\tret = self._oleobj_.InvokeTypes(%d, LCID, %s, %s, %s%s)\n' % (linePrefix, id, fdesc[4], retDesc, repr(argsDesc), _BuildArgList(fdesc, names))
s = s + '%s\tif ret is not None:\n' % (linePrefix,)
if rd == pythoncom.VT_UNKNOWN:
***************
*** 351,366 ****
s = s + "%s\t\texcept pythoncom.error:\n" % (linePrefix,)
s = s + "%s\t\t\treturn ret\n" % (linePrefix,)
! s = s + '%s\t\tret = Dispatch(ret, %s, %s, UnicodeToString=%d)\n' % (linePrefix,`name`, resclsid, NeedUnicodeConversions)
s = s + '%s\treturn ret' % (linePrefix)
elif rd == pythoncom.VT_BSTR:
if NeedUnicodeConversions:
s = "%s\t# Result is a Unicode object - perform automatic string conversion\n" % (linePrefix,)
! s = s + '%s\treturn str(self._oleobj_.InvokeTypes(%d, LCID, %s, %s, %s%s))' % (linePrefix, id, fdesc[4], retDesc, `argsDesc`, _BuildArgList(fdesc, names))
else:
s = "%s\t# Result is a Unicode object - return as-is for this version of Python\n" % (linePrefix,)
! s = s + '%s\treturn self._oleobj_.InvokeTypes(%d, LCID, %s, %s, %s%s)' % (linePrefix, id, fdesc[4], retDesc, `argsDesc`, _BuildArgList(fdesc, names))
# else s remains None
if s is None:
! s = '%s\treturn self._ApplyTypes_(%d, %s, %s, %s, %s, %s%s)' % (linePrefix, id, fdesc[4], retDesc, argsDesc, `name`, resclsid, _BuildArgList(fdesc, names))
ret.append(s)
--- 352,367 ----
s = s + "%s\t\texcept pythoncom.error:\n" % (linePrefix,)
s = s + "%s\t\t\treturn ret\n" % (linePrefix,)
! s = s + '%s\t\tret = Dispatch(ret, %s, %s, UnicodeToString=%d)\n' % (linePrefix,repr(name), resclsid, NeedUnicodeConversions)
s = s + '%s\treturn ret' % (linePrefix)
elif rd == pythoncom.VT_BSTR:
if NeedUnicodeConversions:
s = "%s\t# Result is a Unicode object - perform automatic string conversion\n" % (linePrefix,)
! s = s + '%s\treturn str(self._oleobj_.InvokeTypes(%d, LCID, %s, %s, %s%s))' % (linePrefix, id, fdesc[4], retDesc, repr(argsDesc), _BuildArgList(fdesc, names))
else:
s = "%s\t# Result is a Unicode object - return as-is for this version of Python\n" % (linePrefix,)
! s = s + '%s\treturn self._oleobj_.InvokeTypes(%d, LCID, %s, %s, %s%s)' % (linePrefix, id, fdesc[4], retDesc, repr(argsDesc), _BuildArgList(fdesc, names))
# else s remains None
if s is None:
! s = '%s\treturn self._ApplyTypes_(%d, %s, %s, %s, %s, %s%s)' % (linePrefix, id, fdesc[4], retDesc, argsDesc, repr(name), resclsid, _BuildArgList(fdesc, names))
ret.append(s)
***************
*** 398,402 ****
return cmp(m1.desc[7], m2.desc[7])
! meth_list = self.mapFuncs.values() + self.propMapGet.values() + self.propMapPut.values()
meth_list.sort( cmp_vtable_off )
--- 399,403 ----
return cmp(m1.desc[7], m2.desc[7])
! meth_list = list(self.mapFuncs.values()) + list(self.propMapGet.values()) + list(self.propMapPut.values())
meth_list.sort( cmp_vtable_off )
***************
*** 425,429 ****
# Resolve VT_USERDEFINED (often aliases or typed IDispatches)
! if type(typerepr)==types.TupleType:
indir_vt, subrepr = typerepr
if indir_vt == pythoncom.VT_PTR:
--- 426,430 ----
# Resolve VT_USERDEFINED (often aliases or typed IDispatches)
! if type(typerepr)==tuple:
indir_vt, subrepr = typerepr
if indir_vt == pythoncom.VT_PTR:
***************
*** 435,439 ****
# only when "somehandle" is an object.
# but (VT_PTR, (VT_USERDEFINED, otherhandle)) doesnt get the indirection dropped.
! was_user = type(subrepr)==types.TupleType and subrepr[0]==pythoncom.VT_USERDEFINED
subrepr, sub_clsid, sub_doc = _ResolveType(subrepr, itypeinfo)
if was_user and subrepr in [pythoncom.VT_DISPATCH, pythoncom.VT_UNKNOWN, pythoncom.VT_RECORD]:
--- 436,440 ----
# only when "somehandle" is an object.
# but (VT_PTR, (VT_USERDEFINED, otherhandle)) doesnt get the indirection dropped.
! was_user = type(subrepr)==tuple and subrepr[0]==pythoncom.VT_USERDEFINED
subrepr, sub_clsid, sub_doc = _ResolveType(subrepr, itypeinfo)
if was_user and subrepr in [pythoncom.VT_DISPATCH, pythoncom.VT_UNKNOWN, pythoncom.VT_RECORD]:
***************
*** 493,497 ****
i = names.index(None)
names[i] = "arg%d" % (i,)
! names = map(MakePublicAttributeName, names[1:])
name_num = 0
while len(names) < numArgs:
--- 494,498 ----
i = names.index(None)
names[i] = "arg%d" % (i,)
! names = list(map(MakePublicAttributeName, names[1:]))
name_num = 0
while len(names) < numArgs:
***************
*** 502,506 ****
for i in range(0, len(names), 5):
names[i] = names[i] + "\n\t\t\t"
! return "," + string.join(names, ", ")
valid_identifier_chars = string.ascii_letters + string.digits + "_"
--- 503,507 ----
for i in range(0, len(names), 5):
names[i] = names[i] + "\n\t\t\t"
! return "," + ", ".join(names)
valid_identifier_chars = string.ascii_letters + string.digits + "_"
***************
*** 526,535 ****
return demunge_leading_underscores(className)
elif iskeyword(className): # all keywords are lower case
! return string.capitalize(className)
elif className == 'None':
# assign to None is evil (and SyntaxError in 2.4) - note
# that if it was a global it would get picked up below
className = 'NONE'
! elif is_global and __builtins__.has_key(className):
# builtins may be mixed case. If capitalizing it doesn't change it,
# force to all uppercase (eg, "None", "True" become "NONE", "TRUE"
--- 527,536 ----
return demunge_leading_underscores(className)
elif iskeyword(className): # all keywords are lower case
! return className.capitalize()
elif className == 'None':
# assign to None is evil (and SyntaxError in 2.4) - note
# that if it was a global it would get picked up below
className = 'NONE'
! elif is_global and hasattr(__builtins__, className):
# builtins may be mixed case. If capitalizing it doesn't change it,
# force to all uppercase (eg, "None", "True" become "NONE", "TRUE"
***************
*** 539,543 ****
return ret
# Strip non printable chars
! return filter( lambda char: char in valid_identifier_chars, className)
# Given a default value passed by a type library, return a string with
--- 540,544 ----
return ret
# Strip non printable chars
! return ''.join([char for char in className if char in valid_identifier_chars])
# Given a default value passed by a type library, return a string with
Index: genpy.py
===================================================================
RCS file: /cvsroot/pywin32/pywin32/com/win32com/client/genpy.py,v
retrieving revision 1.55
retrieving revision 1.56
diff -C2 -d -r1.55 -r1.56
*** genpy.py 1 Jul 2008 00:11:14 -0000 1.55
--- genpy.py 14 Nov 2008 00:22:25 -0000 1.56
***************
*** 16,20 ****
import os
import sys
- import string
import time
import win32com
--- 16,19 ----
***************
*** 78,82 ****
def MakeMapLineEntry(dispid, wFlags, retType, argTypes, user, resultCLSID):
# Strip the default value
! argTypes = tuple(map(lambda what: what[:2], argTypes))
return '(%s, %d, %s, %s, "%s", %s)' % \
(dispid, wFlags, retType[:2], argTypes, user, resultCLSID)
--- 77,81 ----
def MakeMapLineEntry(dispid, wFlags, retType, argTypes, user, resultCLSID):
# Strip the default value
! argTypes = tuple([what[:2] for what in argTypes])
return '(%s, %d, %s, %s, "%s", %s)' % \
(dispid, wFlags, retType[:2], argTypes, user, resultCLSID)
***************
*** 105,109 ****
return ret
def __repr__(self):
! return "OleItem: doc=%s, order=%d" % (`self.doc`, self.order)
--- 104,108 ----
return ret
def __repr__(self):
! return "OleItem: doc=%s, order=%d" % (repr(self.doc), self.order)
***************
*** 129,133 ****
# (no longer necessary for new style code, but still used for old code.
def WriteAliasesForItem(item, aliasItems, stream):
! for alias in aliasItems.values():
if item.doc and alias.aliasDoc and (alias.aliasDoc[0]==item.doc[0]):
alias.WriteAliasItem(aliasItems, stream)
--- 128,132 ----
# (no longer necessary for new style code, but still used for old code.
def WriteAliasesForItem(item, aliasItems, stream):
! for alias in aliasItems.itervalues():
if item.doc and alias.aliasDoc and (alias.aliasDoc[0]==item.doc[0]):
alias.WriteAliasItem(aliasItems, stream)
***************
*** 159,163 ****
if self.aliasDoc:
depName = self.aliasDoc[0]
! if aliasDict.has_key(depName):
aliasDict[depName].WriteAliasItem(aliasDict, stream)
print >> stream, self.doc[0] + " = " + depName
--- 158,162 ----
if self.aliasDoc:
depName = self.aliasDoc[0]
! if depName in aliasDict:
aliasDict[depName].WriteAliasItem(aliasDict, stream)
print >> stream, self.doc[0] + " = " + depName
***************
*** 199,203 ****
enumName = self.doc[0]
# Write in name alpha order
! names = self.mapVars.keys()
names.sort()
for name in names:
--- 198,202 ----
enumName = self.doc[0]
# Write in name alpha order
! names = list(self.mapVars.keys())
names.sort()
for name in names:
***************
*** 383,388 ****
continue # Dont build this one now!
else:
! lkey = string.lower(name)
! if specialItems.has_key(lkey) and specialItems[lkey] is None: # remember if a special one.
specialItems[lkey] = (entry, entry.desc[4], None)
if generator.bBuildHidden or not entry.hidden:
--- 382,387 ----
continue # Dont build this one now!
else:
! lkey = name.lower()
! if lkey in specialItems and specialItems[lkey] is None: # remember if a special one.
specialItems[lkey] = (entry, entry.desc[4], None)
if generator.bBuildHidden or not entry.hidden:
***************
*** 402,406 ****
if resultName:
print >> stream, "\t\t# Property '%s' is an object of type '%s'" % (key, resultName)
! lkey = string.lower(key)
details = entry.desc
resultDesc = details[2]
--- 401,405 ----
if resultName:
print >> stream, "\t\t# Property '%s' is an object of type '%s'" % (key, resultName)
! lkey = key.lower()
details = entry.desc
resultDesc = details[2]
***************
*** 413,418 ****
lkey = "_newenum"
else:
! lkey = string.lower(key)
! if specialItems.has_key(lkey) and specialItems[lkey] is None: # remember if a special one.
specialItems[lkey] = (entry, pythoncom.DISPATCH_PROPERTYGET, mapEntry)
# All special methods, except _newenum, are written
--- 412,417 ----
lkey = "_newenum"
else:
! lkey = key.lower()
! if lkey in specialItems and specialItems[lkey] is None: # remember if a special one.
specialItems[lkey] = (entry, pythoncom.DISPATCH_PROPERTYGET, mapEntry)
# All special methods, except _newenum, are written
***************
*** 429,433 ****
print >> stream, "\t\t# Method '%s' returns object of type '%s'" % (key, entry.GetResultName())
details = entry.desc
! lkey = string.lower(key)
argDesc = details[2]
resultDesc = details[8]
--- 428,432 ----
print >> stream, "\t\t# Method '%s' returns object of type '%s'" % (key, entry.GetResultName())
details = entry.desc
! lkey = key.lower()
argDesc = details[2]
resultDesc = details[8]
***************
*** 438,443 ****
lkey = "_newenum"
else:
! lkey = string.lower(key)
! if specialItems.has_key(lkey) and specialItems[lkey] is None: # remember if a special one.
specialItems[lkey]=(entry, pythoncom.DISPATCH_PROPERTYGET, mapEntry)
# All special methods, except _newenum, are written
--- 437,442 ----
lkey = "_newenum"
else:
! lkey = key.lower()
! if lkey in specialItems and specialItems[lkey] is None: # remember if a special one.
specialItems[lkey]=(entry, pythoncom.DISPATCH_PROPERTYGET, mapEntry)
# All special methods, except _newenum, are written
***************
*** 451,459 ****
print >> stream, "\t_prop_map_put_ = {"
# These are "Invoke" args
! names = self.propMap.keys(); names.sort()
for key in names:
entry = self.propMap[key]
if generator.bBuildHidden or not entry.hidden:
! lkey=string.lower(key)
details = entry.desc
# If default arg is None, write an empty tuple
--- 450,458 ----
print >> stream, "\t_prop_map_put_ = {"
# These are "Invoke" args
! names = list(self.propMap.keys()); names.sort()
for key in names:
entry = self.propMap[key]
if generator.bBuildHidden or not entry.hidden:
! lkey=key.lower()
details = entry.desc
# If default arg is None, write an empty tuple
***************
*** 465,469 ****
print >> stream, '\t\t"%s" : ((%s, LCID, %d, 0),(%s)),' % (build.MakePublicAttributeName(key), details[0], pythoncom.DISPATCH_PROPERTYPUT, defArgDesc)
! names = self.propMapPut.keys(); names.sort()
for key in names:
entry = self.propMapPut[key]
--- 464,468 ----
print >> stream, '\t\t"%s" : ((%s, LCID, %d, 0),(%s)),' % (build.MakePublicAttributeName(key), details[0], pythoncom.DISPATCH_PROPERTYPUT, defArgDesc)
! names = list(self.propMapPut.keys()); names.sort()
for key in names:
entry = self.propMapPut[key]
***************
*** 501,505 ****
resultCLSID = enumEntry.GetResultCLSIDStr()
# If we dont have a good CLSID for the enum result, assume it is the same as the Item() method.
! if resultCLSID == "None" and self.mapFuncs.has_key("Item"):
resultCLSID = self.mapFuncs["Item"].GetResultCLSIDStr()
# "Native" Python iterator support
--- 500,504 ----
resultCLSID = enumEntry.GetResultCLSIDStr()
# If we dont have a good CLSID for the enum result, assume it is the same as the Item() method.
! if resultCLSID == "None" and "Item" in self.mapFuncs:
resultCLSID = self.mapFuncs["Item"].GetResultCLSIDStr()
# "Native" Python iterator support
***************
*** 685,689 ****
(refAttr.typekind == pythoncom.TKIND_INTERFACE and refAttr[11] & pythoncom.TYPEFLAG_FDISPATCHABLE):
clsid = refAttr[0]
! if oleItems.has_key(clsid):
dispItem = oleItems[clsid]
else:
--- 684,688 ----
(refAttr.typekind == pythoncom.TKIND_INTERFACE and refAttr[11] & pythoncom.TYPEFLAG_FDISPATCHABLE):
clsid = refAttr[0]
! if clsid in oleItems:
dispItem = oleItems[clsid]
else:
***************
*** 697,701 ****
interfaces[dispItem.clsid] = (dispItem, flags)
# If dual interface, make do that too.
! if not vtableItems.has_key(clsid) and refAttr[11] & pythoncom.TYPEFLAG_FDUAL:
refType = refType.GetRefTypeInfo(refType.GetRefTypeOfImplType(-1))
refAttr = refType.GetTypeAttr()
--- 696,700 ----
interfaces[dispItem.clsid] = (dispItem, flags)
# If dual interface, make do that too.
! if clsid not in vtableItems and refAttr[11] & pythoncom.TYPEFLAG_FDUAL:
refType = refType.GetRefTypeInfo(refType.GetRefTypeOfImplType(-1))
refAttr = refType.GetTypeAttr()
***************
*** 703,708 ****
vtableItem = VTableItem(refType, refAttr, doc)
vtableItems[clsid] = vtableItem
! coclass.sources = sources.values()
! coclass.interfaces = interfaces.values()
def _Build_Interface(self, type_info_tuple):
--- 702,707 ----
vtableItem = VTableItem(refType, refAttr, doc)
vtableItems[clsid] = vtableItem
! coclass.sources = list(sources.values())
! coclass.interfaces = list(interfaces.values())
def _Build_Interface(self, type_info_tuple):
***************
*** 742,746 ****
# hidden, assuming that you only ever use them via the CoClass)
elif infotype in [pythoncom.TKIND_DISPATCH, pythoncom.TKIND_INTERFACE]:
! if not oleItems.has_key(clsid):
oleItem, vtableItem = self._Build_Interface(type_info_tuple)
oleItems[clsid] = oleItem # Even "None" goes in here.
--- 741,745 ----
# hidden, assuming that you only ever use them via the CoClass)
elif infotype in [pythoncom.TKIND_DISPATCH, pythoncom.TKIND_INTERFACE]:
! if clsid not in oleItems:
oleItem, vtableItem = self._Build_Interface(type_info_tuple)
oleItems[clsid] = oleItem # Even "None" goes in here.
Index: gencache.py
===================================================================
RCS file: /cvsroot/pywin32/pywin32/com/win32com/client/gencache.py,v
retrieving revision 1.32
retrieving revision 1.33
diff -C2 -d -r1.32 -r1.33
*** gencache.py 22 Jan 2007 22:18:44 -0000 1.32
--- gencache.py 14 Nov 2008 00:22:25 -0000 1.33
***************
*** 21,25 ****
Maybe an OLE2 compound file, or a bsddb file?
"""
! import pywintypes, os, string, sys
import pythoncom
import win32com, win32com.client
--- 21,25 ----
Maybe an OLE2 compound file, or a bsddb file?
"""
! import pywintypes, os, sys
import pythoncom
import win32com, win32com.client
***************
*** 49,52 ****
--- 49,57 ----
demandGeneratedTypeLibraries = {}
+ try:
+ import cPickle as pickle
+ except ImportError:
+ import pickle
+
def __init__():
# Initialize the module. Called once explicitly at module import below.
***************
*** 59,68 ****
def _SaveDicts():
if is_readonly:
! raise RuntimeError, "Trying to write to a readonly gencache ('%s')!" \
! % win32com.__gen_path__
! import cPickle
f = open(os.path.join(GetGeneratePath(), "dicts.dat"), "wb")
try:
! p = cPickle.Pickler(f)
p.dump(pickleVersion)
p.dump(clsidToTypelib)
--- 64,72 ----
def _SaveDicts():
if is_readonly:
! raise RuntimeError("Trying to write to a readonly gencache ('%s')!" \
! % win32com.__gen_path__)
f = open(os.path.join(GetGeneratePath(), "dicts.dat"), "wb")
try:
! p = pickle.Pickler(f)
p.dump(pickleVersion)
p.dump(clsidToTypelib)
***************
*** 71,78 ****
def _LoadDicts():
- import cPickle
# Load the dictionary from a .zip file if that is where we live.
if hasattr(win32com, "__loader__"):
! import cStringIO
loader = win32com.__loader__
arc_path = loader.archive
--- 75,84 ----
def _LoadDicts():
# Load the dictionary from a .zip file if that is where we live.
if hasattr(win32com, "__loader__"):
! try:
! import cStringIO as io
! except ImportError:
! import io
loader = win32com.__loader__
arc_path = loader.archive
***************
*** 101,110 ****
# the dict)
return
! f = cStringIO.StringIO(data)
else:
# NOTE: IOError on file open must be caught by caller.
f = open(os.path.join(win32com.__gen_path__, "dicts.dat"), "rb")
try:
! p = cPickle.Unpickler(f)
version = p.load()
global clsidToTypelib
--- 107,116 ----
# the dict)
return
! f = io.StringIO(data)
else:
# NOTE: IOError on file open must be caught by caller.
f = open(os.path.join(win32com.__gen_path__, "dicts.dat"), "rb")
try:
! p = pickle.Unpickler(f)
version = p.load()
global clsidToTypelib
***************
*** 118,127 ****
the file name (no extension) providing this support.
"""
! return string.upper(str(clsid))[1:-1] + "x%sx%sx%s" % (lcid, major, minor)
def SplitGeneratedFileName(fname):
"""Reverse of GetGeneratedFileName()
"""
! return tuple(string.split(fname,'x',4))
def GetGeneratePath():
--- 124,133 ----
the file name (no extension) providing this support.
"""
! return str(clsid).upper()[1:-1] + "x%sx%sx%s" % (lcid, major, minor)
def SplitGeneratedFileName(fname):
"""Reverse of GetGeneratedFileName()
"""
! return tuple(fname.split('x',4))
def GetGeneratePath():
***************
*** 235,239 ****
# Force the generation. If this typelibrary has explicitly been added,
# use it (it may not be registered, causing a lookup by clsid to fail)
! if demandGeneratedTypeLibraries.has_key(info):
info = demandGeneratedTypeLibraries[info]
import makepy
--- 241,245 ----
# Force the generation. If this typelibrary has explicitly been added,
# use it (it may not be registered, causing a lookup by clsid to fail)
! if info in demandGeneratedTypeLibraries:
info = demandGeneratedTypeLibraries[info]
import makepy
***************
*** 259,265 ****
# If the import worked, it doesn't mean we have actually added this
# module to our cache though - check that here.
! if not mod.__dict__.has_key("_in_gencache_"):
AddModuleToCache(typelibCLSID, lcid, major, minor)
! assert mod.__dict__.has_key("_in_gencache_")
return mod
--- 265,271 ----
# If the import worked, it doesn't mean we have actually added this
# module to our cache though - check that here.
! if "_in_gencache_" not in mod.__dict__:
AddModuleToCache(typelibCLSID, lcid, major, minor)
! assert "_in_gencache_" in mod.__dict__
return mod
***************
*** 362,366 ****
print "ForgetAboutTypelibInterface:: Warning - type library with info %s is not being remembered!" % (info,)
# and drop any version redirects to it
! for key, val in versionRedirectMap.items():
if val==info:
del versionRedirectMap[key]
--- 368,372 ----
print "ForgetAboutTypelibInterface:: Warning - type library with info %s is not being remembered!" % (info,)
# and drop any version redirects to it
! for key, val in list(versionRedirectMap.items()):
if val==info:
del versionRedirectMap[key]
***************
*** 541,545 ****
disp = disp_class(disp._oleobj_)
except pythoncom.com_error:
! raise TypeError, "This COM object can not automate the makepy process - please run makepy manually for this object"
return disp
--- 547,551 ----
disp = disp_class(disp._oleobj_)
except pythoncom.com_error:
! raise TypeError("This COM object can not automate the makepy process - please run makepy manually for this object")
return disp
***************
*** 554,574 ****
dict = mod.CLSIDToClassMap
info = str(typelibclsid), lcid, major, minor
! for clsid, cls in dict.items():
clsidToTypelib[clsid] = info
dict = mod.CLSIDToPackageMap
! for clsid, name in dict.items():
clsidToTypelib[clsid] = info
dict = mod.VTablesToClassMap
! for clsid, cls in dict.items():
clsidToTypelib[clsid] = info
dict = mod.VTablesToPackageMap
! for clsid, cls in dict.items():
clsidToTypelib[clsid] = info
# If this lib was previously redirected, drop it
! if versionRedirectMap.has_key(info):
del versionRedirectMap[info]
if bFlushNow:
--- 560,580 ----
dict = mod.CLSIDToClassMap
info = str(typelibclsid), lcid, major, minor
! for clsid, cls in dict.iteritems():
clsidToTypelib[clsid] = info
dict = mod.CLSIDToPackageMap
! for clsid, name in dict.iteritems():
clsidToTypelib[clsid] = info
dict = mod.VTablesToClassMap
! for clsid, cls in dict.iteritems():
clsidToTypelib[clsid] = info
dict = mod.VTablesToPackageMap
! for clsid, cls in dict.iteritems():
clsidToTypelib[clsid] = info
# If this lib was previously redirected, drop it
! if info in versionRedirectMap:
del versionRedirectMap[info]
if bFlushNow:
***************
*** 578,582 ****
zip_pos = win32com.__gen_path__.find(".zip\\")
if zip_pos >= 0:
! import zipfile, cStringIO
zip_file = win32com.__gen_path__[:zip_pos+4]
zip_path = win32com.__gen_path__[zip_pos+5:].replace("\\", "/")
--- 584,588 ----
zip_pos = win32com.__gen_path__.find(".zip\\")
if zip_pos >= 0:
! import zipfile
zip_file = win32com.__gen_path__[:zip_pos+4]
zip_path = win32com.__gen_path__[zip_pos+5:].replace("\\", "/")
***************
*** 600,604 ****
infos[(iid, lcid, major, minor)] = 1
zf.close()
! return infos.keys()
else:
# on the file system
--- 606,610 ----
infos[(iid, lcid, major, minor)] = 1
zf.close()
! return list(infos.keys())
else:
# on the file system
***************
*** 610,614 ****
name = os.path.splitext(os.path.split(file)[1])[0]
try:
! iid, lcid, major, minor = string.split(name, "x")
iid = pywintypes.IID("{" + iid + "}")
lcid = int(lcid)
--- 616,620 ----
name = os.path.splitext(os.path.split(file)[1])[0]
try:
! iid, lcid, major, minor = name.split("x")
iid = pywintypes.IID("{" + iid + "}")
lcid = int(lcid)
***************
*** 653,659 ****
# Build a unique dir
d = {}
! for clsid, (typelibCLSID, lcid, major, minor) in clsidToTypelib.items():
d[typelibCLSID, lcid, major, minor] = None
! for typelibCLSID, lcid, major, minor in d.keys():
mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
print "%s - %s" % (mod.__doc__, typelibCLSID)
--- 659,665 ----
# Build a unique dir
d = {}
! for clsid, (typelibCLSID, lcid, major, minor) in clsidToTypelib.iteritems():
d[typelibCLSID, lcid, major, minor] = None
! for typelibCLSID, lcid, major, minor in d.iterkeys():
mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
print "%s - %s" % (mod.__doc__, typelibCLSID)
Index: selecttlb.py
===================================================================
RCS file: /cvsroot/pywin32/pywin32/com/win32com/client/selecttlb.py,v
retrieving revision 1.10
retrieving revision 1.11
diff -C2 -d -r1.10 -r1.11
*** selecttlb.py 17 Oct 2007 03:51:57 -0000 1.10
--- selecttlb.py 14 Nov 2008 00:22:25 -0000 1.11
***************
*** 2,6 ****
"""
! import win32api, win32con, string, pythoncom
class TypelibSpec:
--- 2,6 ----
"""
! import win32api, win32con, pythoncom
class TypelibSpec:
***************
*** 22,30 ****
if item==0:
return self.ver_desc
! raise IndexError, "Cant index me!"
def __cmp__(self, other):
! rc = cmp(string.lower(self.ver_desc or ""), string.lower(other.ver_desc or ""))
if rc==0:
! rc = cmp(string.lower(self.desc), string.lower(other.desc))
if rc==0:
rc = cmp(self.major, other.major)
--- 22,30 ----
if item==0:
return self.ver_desc
! raise IndexError("Cant index me!")
def __cmp__(self, other):
! rc = cmp((self.ver_desc or "").lower(), (other.ver_desc or "").lower())
if rc==0:
! rc = cmp(self.desc.lower(), other.desc.lower())
if rc==0:
rc = cmp(self.major, other.major)
***************
*** 85,89 ****
continue
for version, tlbdesc in EnumKeys(key2):
! major_minor = string.split(version, '.', 1)
if len(major_minor) < 2:
major_minor.append('0')
--- 85,89 ----
continue
for version, tlbdesc in EnumKeys(key2):
! major_minor = version.split('.', 1)
if len(major_minor) < 2:
major_minor.append('0')
Index: CLSIDToClass.py
===================================================================
RCS file: /cvsroot/pywin32/pywin32/com/win32com/client/CLSIDToClass.py,v
retrieving revision 1.2
retrieving revision 1.3
diff -C2 -d -r1.2 -r1.3
*** CLSIDToClass.py 23 Oct 2008 03:40:36 -0000 1.2
--- CLSIDToClass.py 14 Nov 2008 00:22:25 -0000 1.3
***************
*** 51,53 ****
clsid -- the string CLSID to check
"""
! return mapCLSIDToClass.has_key(clsid)
--- 51,53 ----
clsid -- the string CLSID to check
"""
! return clsid in mapCLSIDToClass
|