BaseTools: Fix old python2 idioms

Based on "futurize -f lib2to3.fixes.fix_idioms"

* Change some type comparisons to isinstance() calls:
    type(x) == T -> isinstance(x, T)
    type(x) is T -> isinstance(x, T)
    type(x) != T -> not isinstance(x, T)
    type(x) is not T -> not isinstance(x, T)

* Change "while 1:" into "while True:".

* Change both

    v = list(EXPR)
    v.sort()
    foo(v)

and the more general

    v = EXPR
    v.sort()
    foo(v)

into

    v = sorted(EXPR)
    foo(v)

Contributed-under: TianoCore Contribution Agreement 1.1
Cc: Yonghong Zhu <yonghong.zhu@intel.com>
Cc: Liming Gao <liming.gao@intel.com>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Yonghong Zhu <yonghong.zhu@intel.com>
This commit is contained in:
Gary Lin
2018-06-25 18:31:35 +08:00
committed by Yonghong Zhu
parent 2617a73c36
commit 0d1f5b2b5d
31 changed files with 93 additions and 111 deletions

View File

@ -245,12 +245,12 @@ class ValueExpression(BaseExpression):
WrnExp = None
if Operator not in {"==", "!=", ">=", "<=", ">", "<", "in", "not in"} and \
(type(Oprand1) == type('') or type(Oprand2) == type('')):
(isinstance(Oprand1, type('')) or isinstance(Oprand2, type(''))):
raise BadExpression(ERR_STRING_EXPR % Operator)
if Operator in {'in', 'not in'}:
if type(Oprand1) != type(''):
if not isinstance(Oprand1, type('')):
Oprand1 = IntToStr(Oprand1)
if type(Oprand2) != type(''):
if not isinstance(Oprand2, type('')):
Oprand2 = IntToStr(Oprand2)
TypeDict = {
type(0) : 0,
@ -261,18 +261,18 @@ class ValueExpression(BaseExpression):
EvalStr = ''
if Operator in {"!", "NOT", "not"}:
if type(Oprand1) == type(''):
if isinstance(Oprand1, type('')):
raise BadExpression(ERR_STRING_EXPR % Operator)
EvalStr = 'not Oprand1'
elif Operator in {"~"}:
if type(Oprand1) == type(''):
if isinstance(Oprand1, type('')):
raise BadExpression(ERR_STRING_EXPR % Operator)
EvalStr = '~ Oprand1'
else:
if Operator in {"+", "-"} and (type(True) in {type(Oprand1), type(Oprand2)}):
# Boolean in '+'/'-' will be evaluated but raise warning
WrnExp = WrnExpression(WRN_BOOL_EXPR)
elif type('') in {type(Oprand1), type(Oprand2)} and type(Oprand1)!= type(Oprand2):
elif type('') in {type(Oprand1), type(Oprand2)} and not isinstance(Oprand1, type(Oprand2)):
# == between string and number/boolean will always return False, != return True
if Operator == "==":
WrnExp = WrnExpression(WRN_EQCMP_STR_OTHERS)
@ -293,11 +293,11 @@ class ValueExpression(BaseExpression):
pass
else:
raise BadExpression(ERR_EXPR_TYPE)
if type(Oprand1) == type('') and type(Oprand2) == type(''):
if isinstance(Oprand1, type('')) and isinstance(Oprand2, type('')):
if (Oprand1.startswith('L"') and not Oprand2.startswith('L"')) or \
(not Oprand1.startswith('L"') and Oprand2.startswith('L"')):
raise BadExpression(ERR_STRING_CMP % (Oprand1, Operator, Oprand2))
if 'in' in Operator and type(Oprand2) == type(''):
if 'in' in Operator and isinstance(Oprand2, type('')):
Oprand2 = Oprand2.split()
EvalStr = 'Oprand1 ' + Operator + ' Oprand2'
@ -325,7 +325,7 @@ class ValueExpression(BaseExpression):
def __init__(self, Expression, SymbolTable={}):
super(ValueExpression, self).__init__(self, Expression, SymbolTable)
self._NoProcess = False
if type(Expression) != type(''):
if not isinstance(Expression, type('')):
self._Expr = Expression
self._NoProcess = True
return
@ -373,7 +373,7 @@ class ValueExpression(BaseExpression):
Token = self._GetToken()
except BadExpression:
pass
if type(Token) == type('') and Token.startswith('{') and Token.endswith('}') and self._Idx >= self._Len:
if isinstance(Token, type('')) and Token.startswith('{') and Token.endswith('}') and self._Idx >= self._Len:
return self._Expr
self._Idx = 0
@ -381,7 +381,7 @@ class ValueExpression(BaseExpression):
Val = self._ConExpr()
RealVal = Val
if type(Val) == type(''):
if isinstance(Val, type('')):
if Val == 'L""':
Val = False
elif not Val:
@ -640,7 +640,7 @@ class ValueExpression(BaseExpression):
Ex.Pcd = self._Token
raise Ex
self._Token = ValueExpression(self._Symb[self._Token], self._Symb)(True, self._Depth+1)
if type(self._Token) != type(''):
if not isinstance(self._Token, type('')):
self._LiteralToken = hex(self._Token)
return
@ -735,7 +735,7 @@ class ValueExpression(BaseExpression):
if Ch == ')':
TmpValue = self._Expr[Idx :self._Idx - 1]
TmpValue = ValueExpression(TmpValue)(True)
TmpValue = '0x%x' % int(TmpValue) if type(TmpValue) != type('') else TmpValue
TmpValue = '0x%x' % int(TmpValue) if not isinstance(TmpValue, type('')) else TmpValue
break
self._Token, Size = ParseFieldValue(Prefix + '(' + TmpValue + ')')
return self._Token
@ -824,7 +824,7 @@ class ValueExpressionEx(ValueExpression):
PcdValue = PcdValue.strip()
if PcdValue.startswith('{') and PcdValue.endswith('}'):
PcdValue = SplitPcdValueString(PcdValue[1:-1])
if type(PcdValue) == type([]):
if isinstance(PcdValue, type([])):
TmpValue = 0
Size = 0
ValueType = ''
@ -863,7 +863,7 @@ class ValueExpressionEx(ValueExpression):
else:
ItemValue = ParseFieldValue(Item)[0]
if type(ItemValue) == type(''):
if isinstance(ItemValue, type('')):
ItemValue = int(ItemValue, 0)
TmpValue = (ItemValue << (Size * 8)) | TmpValue
@ -873,7 +873,7 @@ class ValueExpressionEx(ValueExpression):
TmpValue, Size = ParseFieldValue(PcdValue)
except BadExpression as Value:
raise BadExpression("Type: %s, Value: %s, %s" % (self.PcdType, PcdValue, Value))
if type(TmpValue) == type(''):
if isinstance(TmpValue, type('')):
try:
TmpValue = int(TmpValue)
except:
@ -996,7 +996,7 @@ class ValueExpressionEx(ValueExpression):
TmpValue = ValueExpressionEx(Item, ValueType, self._Symb)(True)
else:
TmpValue = ValueExpressionEx(Item, self.PcdType, self._Symb)(True)
Item = '0x%x' % TmpValue if type(TmpValue) != type('') else TmpValue
Item = '0x%x' % TmpValue if not isinstance(TmpValue, type('')) else TmpValue
if ItemSize == 0:
ItemValue, ItemSize = ParseFieldValue(Item)
if Item[0] not in {'"', 'L', '{'} and ItemSize > 1:

View File

@ -1291,9 +1291,9 @@ def ParseDevPathValue (Value):
return '{' + out + '}', Size
def ParseFieldValue (Value):
if type(Value) == type(0):
if isinstance(Value, type(0)):
return Value, (Value.bit_length() + 7) / 8
if type(Value) != type(''):
if not isinstance(Value, type('')):
raise BadExpression('Type %s is %s' %(Value, type(Value)))
Value = Value.strip()
if Value.startswith(TAB_UINT8) and Value.endswith(')'):
@ -1584,8 +1584,7 @@ def CheckPcdDatum(Type, Value):
Printset.add(TAB_PRINTCHAR_BS)
Printset.add(TAB_PRINTCHAR_NUL)
if not set(Value).issubset(Printset):
PrintList = list(Printset)
PrintList.sort()
PrintList = sorted(Printset)
return False, "Invalid PCD string value of type [%s]; must be printable chars %s." % (Type, PrintList)
elif Type == 'BOOLEAN':
if Value not in ['TRUE', 'True', 'true', '0x1', '0x01', '1', 'FALSE', 'False', 'false', '0x0', '0x00', '0']:
@ -1747,7 +1746,7 @@ class PathClass(object):
# @retval True The two PathClass are the same
#
def __eq__(self, Other):
if type(Other) == type(self):
if isinstance(Other, type(self)):
return self.Path == Other.Path
else:
return self.Path == str(Other)
@ -1760,7 +1759,7 @@ class PathClass(object):
# @retval -1 The first PathClass is less than the second PathClass
# @retval 1 The first PathClass is Bigger than the second PathClass
def __cmp__(self, Other):
if type(Other) == type(self):
if isinstance(Other, type(self)):
OtherKey = Other.Path
else:
OtherKey = str(Other)
@ -2010,7 +2009,7 @@ class SkuClass():
return ["DEFAULT"]
skulist = [sku]
nextsku = sku
while 1:
while True:
nextsku = self.GetNextSkuId(nextsku)
skulist.append(nextsku)
if nextsku == "DEFAULT":

View File

@ -97,7 +97,7 @@ class XOROperatorObject(object):
def __init__(self):
pass
def Calculate(self, Operand, DataType, SymbolTable):
if type(Operand) == type('') and not Operand.isalnum():
if isinstance(Operand, type('')) and not Operand.isalnum():
Expr = "XOR ..."
raise BadExpression(ERR_SNYTAX % Expr)
rangeId = str(uuid.uuid1())
@ -111,7 +111,7 @@ class LEOperatorObject(object):
def __init__(self):
pass
def Calculate(self, Operand, DataType, SymbolTable):
if type(Operand) == type('') and not Operand.isalnum():
if isinstance(Operand, type('')) and not Operand.isalnum():
Expr = "LE ..."
raise BadExpression(ERR_SNYTAX % Expr)
rangeId1 = str(uuid.uuid1())
@ -123,7 +123,7 @@ class LTOperatorObject(object):
def __init__(self):
pass
def Calculate(self, Operand, DataType, SymbolTable):
if type(Operand) == type('') and not Operand.isalnum():
if isinstance(Operand, type('')) and not Operand.isalnum():
Expr = "LT ..."
raise BadExpression(ERR_SNYTAX % Expr)
rangeId1 = str(uuid.uuid1())
@ -136,7 +136,7 @@ class GEOperatorObject(object):
def __init__(self):
pass
def Calculate(self, Operand, DataType, SymbolTable):
if type(Operand) == type('') and not Operand.isalnum():
if isinstance(Operand, type('')) and not Operand.isalnum():
Expr = "GE ..."
raise BadExpression(ERR_SNYTAX % Expr)
rangeId1 = str(uuid.uuid1())
@ -149,7 +149,7 @@ class GTOperatorObject(object):
def __init__(self):
pass
def Calculate(self, Operand, DataType, SymbolTable):
if type(Operand) == type('') and not Operand.isalnum():
if isinstance(Operand, type('')) and not Operand.isalnum():
Expr = "GT ..."
raise BadExpression(ERR_SNYTAX % Expr)
rangeId1 = str(uuid.uuid1())
@ -162,7 +162,7 @@ class EQOperatorObject(object):
def __init__(self):
pass
def Calculate(self, Operand, DataType, SymbolTable):
if type(Operand) == type('') and not Operand.isalnum():
if isinstance(Operand, type('')) and not Operand.isalnum():
Expr = "EQ ..."
raise BadExpression(ERR_SNYTAX % Expr)
rangeId1 = str(uuid.uuid1())
@ -350,7 +350,7 @@ class RangeExpression(BaseExpression):
def __init__(self, Expression, PcdDataType, SymbolTable = {}):
super(RangeExpression, self).__init__(self, Expression, PcdDataType, SymbolTable)
self._NoProcess = False
if type(Expression) != type(''):
if not isinstance(Expression, type('')):
self._Expr = Expression
self._NoProcess = True
return
@ -571,7 +571,7 @@ class RangeExpression(BaseExpression):
Ex.Pcd = self._Token
raise Ex
self._Token = RangeExpression(self._Symb[self._Token], self._Symb)(True, self._Depth + 1)
if type(self._Token) != type(''):
if not isinstance(self._Token, type('')):
self._LiteralToken = hex(self._Token)
return

View File

@ -251,7 +251,7 @@ def SplitModuleType(Key):
def ReplaceMacros(StringList, MacroDefinitions={}, SelfReplacement=False):
NewList = []
for String in StringList:
if type(String) == type(''):
if isinstance(String, type('')):
NewList.append(ReplaceMacro(String, MacroDefinitions, SelfReplacement))
else:
NewList.append(String)
@ -793,7 +793,7 @@ def RemoveBlockComment(Lines):
# Get String of a List
#
def GetStringOfList(List, Split=' '):
if type(List) != type([]):
if not isinstance(List, type([])):
return List
Str = ''
for Item in List:

View File

@ -158,7 +158,7 @@ class ToolDefClassObject(object):
if ErrorCode != 0:
EdkLogger.error("tools_def.txt parser", FILE_NOT_FOUND, ExtraData=IncFile)
if type(IncFileTmp) is PathClass:
if isinstance(IncFileTmp, PathClass):
IncFile = IncFileTmp.Path
else:
IncFile = IncFileTmp

View File

@ -127,8 +127,7 @@ class VpdInfoFile:
"Invalid parameter FilePath: %s." % FilePath)
Content = FILE_COMMENT_TEMPLATE
Pcds = self._VpdArray.keys()
Pcds.sort()
Pcds = sorted(self._VpdArray.keys())
for Pcd in Pcds:
i = 0
PcdTokenCName = Pcd.TokenCName