Commit 7f38ce35 authored by Wolfgang Rohdewald's avatar Wolfgang Rohdewald
Browse files

pylint: remove unneeded else

parent 1aea8814
......@@ -81,8 +81,7 @@ class Animation(QPropertyAnimation, StrMixin):
pGroup = self.group() if isAlive(self) else 'notAlive'
if pGroup or not isAlive(self):
return '%s/A%s' % (pGroup, id4(self))
else:
return 'A%s-%s' % (id4(self), self.targetObject().name())
return 'A%s-%s' % (id4(self), self.targetObject().name())
def pName(self):
"""
......@@ -90,10 +89,9 @@ class Animation(QPropertyAnimation, StrMixin):
@return: C{str}
"""
if isAlive(self):
return bytes(self.propertyName()).decode()
else:
if not isAlive(self):
return 'notAlive'
return bytes(self.propertyName()).decode()
def formatValue(self, value):
"""string format the wanted value from qvariant"""
......
......@@ -43,8 +43,7 @@ class ChatModel(QAbstractTableModel):
if orientation == Qt.Horizontal:
if section == 1:
return int(Qt.AlignRight)
else:
return int(Qt.AlignLeft)
return int(Qt.AlignLeft)
if orientation != Qt.Horizontal:
return int(section + 1)
if role != Qt.DisplayRole:
......@@ -71,8 +70,7 @@ class ChatModel(QAbstractTableModel):
if role == Qt.TextAlignmentRole:
if index.column() == 1:
return int(Qt.AlignRight)
else:
return int(Qt.AlignLeft)
return int(Qt.AlignLeft)
if index.isValid() and (0 <= index.row() < len(self.chatLines)):
chatLine = self.chatLines[index.row()]
if role == Qt.DisplayRole and index.column() == 0:
......
......@@ -351,10 +351,7 @@ class Client(pb.Referenceable):
@staticmethod
def __jellyMessage(value):
"""the Message classes are not pb.copyable, convert them into their names"""
if value is None:
return Message.OK.name
else:
return Message.jelly(value, value)
return Message.OK.name if value is None else Message.jelly(value, value)
def remote_move(self, playerName, command, *unusedArgs, **kwargs): # pylint: disable=unused-argument
"""the server sends us info or a question and always wants us to answer"""
......@@ -431,10 +428,9 @@ class Client(pb.Referenceable):
# 4. but this answer is Chow, without a selected Chow. This is
# wrongly sent to server
return answer
else:
# return answer only after animation ends. Put answer into
# the Deferred returned by animate().
return animate().addCallback(lambda x: answer)
# return answer only after animation ends. Put answer into
# the Deferred returned by animate().
return animate().addCallback(lambda x: answer)
def claimed(self, move):
"""somebody claimed a discarded tile"""
......
......@@ -126,8 +126,7 @@ def socketName():
# there
if Options.socket:
return Options.socket
else:
return os.path.normpath('{}/socket{}'.format(serverDir, Internal.defaultPort))
return os.path.normpath('{}/socket{}'.format(serverDir, Internal.defaultPort))
class Debug:
......@@ -257,8 +256,7 @@ class StrMixin:
content = str(self)
if content.startswith(clsName):
return content
else:
return '{cls}({content})'.format(cls=clsName, content=content)
return '{cls}({content})'.format(cls=clsName, content=content)
class Options:
......
......@@ -974,12 +974,9 @@ class PlayingGame(Game):
def _mustExchangeSeats(self, pairs):
"""filter: which player pairs should really swap places?"""
if self.belongsToPlayer():
# if we are a client in a remote game, the server swaps and tells
# us the new places
return []
else:
return pairs
# if we are a client in a remote game, the server swaps and tells
# us the new places
return [] if self.belongsToPlayer() else pairs
def _scanGameOption(self):
"""scan the --game option and go to start of wanted hand"""
......
......@@ -208,10 +208,7 @@ class Games(QDialog):
def __getSelectedGame(self):
"""returns the game id of the selected game"""
rows = self.selection.selectedRows()
if rows:
return self.model.data(rows[0], 0)
else:
return 0
return self.model.data(rows[0], 0) if rows else 0
def pendingOrNot(self, chosen):
"""do we want to see all games or only pending games?"""
......
......@@ -658,9 +658,8 @@ class Hand(StrMixin):
return True
elif not (self.arranged and self.won) and other.won:
return False
else:
return (self.intelligence.handValue(self)
> self.intelligence.handValue(other))
return (self.intelligence.handValue(self)
> self.intelligence.handValue(other))
def __lt__(self, other):
"""compares hand values"""
......
......@@ -59,10 +59,7 @@ class TileAttr(StrMixin):
def setDark(self):
"""should the tile appear darker?"""
if self.yoffset == 0:
return self.tile.isConcealed
else:
return not self.tile.isKnown
return self.tile.isConcealed if self.yoffset == 0 else not self.tile.isKnown
def setFocusable(self, hand, meld, unusedIdx):
"""is it focusable?"""
......
......@@ -617,8 +617,7 @@ class HumanClient(Client):
if self.connection and result:
# still connected and yes, we are
return clientReady()
else:
return Message.NoGameStart
return Message.NoGameStart
def cancelled(unused):
"""the user does not want to start now. Back to table list"""
......@@ -746,8 +745,7 @@ class HumanClient(Client):
# this does not specify any tiles, the server does not need this. Robot players
# also return None in this case.
return answer
else:
return answer, args
return answer, args
def __answerError(self, answer, move, answers):
"""an error happened while determining the answer to server"""
......
......@@ -77,8 +77,7 @@ class OptionHelper:
"""did the user specify this option?"""
if any(x[0].startswith('no%s' % option) for x in self.options):
return not any(x.startswith('--no%s' % option) for x in sys.argv)
else:
return any(x.startswith('--%s' % option) for x in sys.argv)
return any(x.startswith('--%s' % option) for x in sys.argv)
@staticmethod
def getOption(option):
......@@ -86,16 +85,10 @@ class OptionHelper:
for arg in sys.argv:
if arg.startswith('--%s' % option):
parts = arg.split('=')
if len(parts) > 1:
return parts[1]
else:
return True
return parts[1] if len(parts) > 1 else True
if arg.startswith('--no%s' % option):
parts = arg.split('=')
if len(parts) > 1:
return parts[1]
else:
return False
return parts[1] if len(parts) > 1 else False
return ''
......@@ -438,9 +431,7 @@ class KUser:
"""stub"""
if os.name == 'nt':
return self.loginName()
else:
return pwd.getpwnam(self.loginName()).pw_gecos.replace(',', '')
return None
return pwd.getpwnam(self.loginName()).pw_gecos.replace(',', '')
@staticmethod
def loginName():
......@@ -709,8 +700,7 @@ class KConfigGroup:
':') if MLocale.isLanguageInstalled(x))
if languages:
return ':'.join(languages)
else:
return QLocale().name()
return QLocale().name()
return items[name]
return self.__default(name, default)
......@@ -787,8 +777,7 @@ def KIcon(name=None): # pylint: disable=invalid-name
"""simple wrapper"""
if os.name == 'nt':
return QIcon(os.path.join('share', 'icons', name) if name else None)
else:
return QIcon.fromTheme(name)
return QIcon.fromTheme(name)
class KConfigSkeletonItem:
......
......@@ -62,8 +62,7 @@ class Fmt(string.Formatter):
return 'None'
elif Debug.neutral:
return '....'
else:
return Fmt.num_encode(id(kwargs[idpar]))
return Fmt.num_encode(id(kwargs[idpar]))
elif key == 'self':
return kwargs['SELF']
else:
......@@ -125,9 +124,8 @@ def dbgIndent(this, parent):
"""show messages indented"""
if this.indent == 0:
return ''
else:
pIndent = parent.indent if parent else 0
return (' │ ' * (pIndent)) + ' ├' + '─' * (this.indent - pIndent - 1)
pIndent = parent.indent if parent else 0
return (' │ ' * (pIndent)) + ' ├' + '─' * (this.indent - pIndent - 1)
def __logUnicodeMessage(prio, msg):
......@@ -213,10 +211,7 @@ def logMessage(msg, prio, showDialog, showStack=False, withGamePrefix=True):
if int(Debug.callers):
__logUnicodeMessage(prio, callers(int(Debug.callers)))
if showDialog and not Internal.isServer:
if prio == logging.INFO:
return Information(msg)
else:
return Sorry(msg, always=True)
return Information(msg) if prio == logging.INFO else Sorry(msg, always=True)
return NoPrompt(msg)
......
......@@ -90,10 +90,7 @@ class Url(str, StrMixin):
def __str__(self):
"""show all info"""
if self.useSocket:
return socketName()
else:
return '{}:{}'.format(self.host, self.port)
return socketName() if self.useSocket else '{}:{}'.format(self.host, self.port)
@property
def useSocket(self):
......@@ -240,9 +237,8 @@ class Url(str, StrMixin):
"""returns a twisted connector"""
if self.useSocket:
return Internal.reactor.connectUNIX(socketName(), factory, timeout=5)
else:
host = self.host
return Internal.reactor.connectTCP(host, self.port, factory, timeout=5)
host = self.host
return Internal.reactor.connectTCP(host, self.port, factory, timeout=5)
class LoginDlg(QDialog):
......@@ -358,8 +354,7 @@ class LoginDlg(QDialog):
return Options.ruleset
elif Internal.autoPlay or bool(Options.host):
return Ruleset.selectableRulesets()[0]
else:
return self.cbRuleset.current
return self.cbRuleset.current
def userChanged(self, text):
"""the username has been changed, lookup password"""
......@@ -596,20 +591,15 @@ class Connection:
"""login failed"""
def answered(result):
"""user finally answered our question"""
if result:
return self.__adduser()
else:
return Failure(CancelledError())
return self.__adduser() if result else Failure(CancelledError())
message = failure.getErrorMessage()
if 'Wrong username' in message:
if self.url.isLocalHost:
return answered(True)
else:
msg = i18nc('USER is not known on SERVER',
'%1 is not known on %2, do you want to open an account?', self.dlg.username, self.url.host)
return QuestionYesNo(msg).addCallback(answered)
else:
return self._loginReallyFailed(failure)
msg = i18nc('USER is not known on SERVER',
'%1 is not known on %2, do you want to open an account?', self.dlg.username, self.url.host)
return QuestionYesNo(msg).addCallback(answered)
return self._loginReallyFailed(failure)
def _loginReallyFailed(self, failure):
"""login failed, not fixable by adding missing user"""
......
......@@ -243,8 +243,7 @@ class Meld(TileList, StrMixin):
return True
elif len(self) == 4:
return self.case[1:3].islower()
else:
return False
return False
def __setMeldType(self):
"""compute meld type. Except knitting melds."""
......@@ -341,8 +340,7 @@ class Meld(TileList, StrMixin):
return i18nc('kajongg meld type', 'c&laimed kong')
elif self.isKong:
return i18nc('kajongg meld type', 'k&ong')
else:
return i18nc('kajongg meld type', 'rest of tiles')
return i18nc('kajongg meld type', 'rest of tiles')
def __stateName(self):
"""the translated name of the state"""
......@@ -350,8 +348,7 @@ class Meld(TileList, StrMixin):
return ''
elif self.isExposed:
return i18nc('kajongg meld state', 'Exposed')
else:
return i18nc('kajongg meld state', 'Concealed')
return i18nc('kajongg meld state', 'Concealed')
def name(self):
"""the long name"""
......@@ -429,7 +426,6 @@ class MeldList(list):
def __str__(self):
if self:
return ' '.join(str(x) for x in self)
else:
return ''
return ''
Meld.cacheMeldsInTiles()
......@@ -191,8 +191,7 @@ class NotifyAtOnceMessage(ClientMessage):
game = request.block.table.game
if game:
return list(x for x in game.players if x != request.player)
else:
return []
return []
class PungChowMessage(NotifyAtOnceMessage):
......@@ -289,10 +288,7 @@ class MessageKong(NotifyAtOnceMessage, ServerMessage):
def clientAction(self, client, move):
"""mirror kong call"""
if client.game.lastDiscard:
return client.claimed(move)
else:
return client.declared(move)
return client.claimed(move) if client.game.lastDiscard else client.declared(move)
class MessageChow(PungChowMessage, ServerMessage):
......@@ -375,11 +371,10 @@ class MessageOriginalCall(NotifyAtOnceMessage, ServerMessage):
'discarding %1 and declaring Original Call makes this hand unwinnable',
tile.name())
return txt, True, txt
else:
return (i18n(
'Discard a tile, declaring Original Call meaning you need only one '
'tile to complete the hand and will not alter the hand in any way (except bonus tiles)'),
False, '')
return (i18n(
'Discard a tile, declaring Original Call meaning you need only one '
'tile to complete the hand and will not alter the hand in any way (except bonus tiles)'),
False, '')
def clientAction(self, client, move):
"""mirror the original call"""
......@@ -586,10 +581,7 @@ class MessagePickedTile(ServerMessage):
assert move.player.pickedTile(move.deadEnd, tileName=move.tile) == move.tile, \
(move.player.lastTile, move.tile)
if client.thatWasMe(move.player):
if move.tile.isBonus:
return Message.Bonus, move.tile
else:
return client.myAction(move)
return (Message.Bonus, move.tile) if move.tile.isBonus else client.myAction(move)
class MessageActivePlayer(ServerMessage):
......
......@@ -38,10 +38,9 @@ class Permutations:
cacheKey = tuple(x.key for x in tiles)
if cacheKey in cls.cache:
return cls.cache[cacheKey]
else:
result = object.__new__(cls)
cls.cache[cacheKey] = result
return result
result = object.__new__(cls)
cls.cache[cacheKey] = result
return result
def __init__(self, tiles):
self.tiles = tiles
......
......@@ -296,10 +296,7 @@ class Player(StrMixin):
@property
def handTotal(self):
"""the hand total of this player for the final scoring"""
if not self.game.winner:
return 0
else:
return self.hand.total()
return 0 if not self.game.winner else self.hand.total()
@property
def balance(self):
......@@ -637,8 +634,7 @@ class PlayingPlayer(Player):
where a meld is represented by a list of 2char strings"""
if msg in (Message.Chow, Message.Pung, Message.Kong):
return [x for x in self.sayable[msg] if self.mustPlayDangerous(x)]
else:
return []
return []
def hasConcealedTiles(self, tiles, within=None):
"""do I have those concealed tiles?"""
......
......@@ -75,10 +75,7 @@ class PlayerList(QDialog):
@staticmethod
def sortKey(text):
"""display order in Table"""
if not text:
return 'zzzzzzzzzzzz'
else:
return text.upper()
return text.upper() if text else 'zzzzzzzzzzzz'
def updateTable(self, data=None, currentName=None):
"""fills self.table from DB"""
......
......@@ -105,8 +105,7 @@ class DBCursor(sqlite3.Cursor):
"""the statement"""
if self.parameters is not None:
return "{cmd} [{args}]".format(cmd=self.statement, args=self.parameters)
else:
return self.statement
return self.statement
class DBHandle(sqlite3.Connection):
......@@ -272,10 +271,7 @@ class Query:
def rowcount(self):
"""how many rows were affected?"""
if self.cursor:
return self.cursor.rowcount
else:
return 0
return self.cursor.rowcount if self.cursor else 0
def initDb():
......@@ -391,8 +387,7 @@ class PrepareDB:
"""
if Internal.db.tableHasField('general', 'schemaversion'):
return Query('select schemaversion from general').records[0][0]
else:
return '1.1.1'
return '1.1.1'
def __upgrade(self):
"""upgrade the structure of an existing kajongg database"""
......
......@@ -518,10 +518,7 @@ class WrigglingSnake(MJRule):
and all(not x.isChow for x in hand.declaredMelds))
def computeLastMelds(hand):
if hand.lastTile.value == 1:
return [hand.lastTile.pair]
else:
return [hand.lastTile.single]
return [hand.lastTile.pair] if hand.lastTile.value == 1 else [hand.lastTile.single]
def winningTileCandidates(hand):
suits = hand.suits.copy()
......@@ -539,12 +536,10 @@ class WrigglingSnake(MJRule):
if hand.values.count(1) < 2:
# and the pair of 1 is incomplete too
return set()
else:
return (elements.winds | set([Tile(group, x) for x in range(2, 10)])) \
- set([x.exposed for x in hand.tiles])
else:
# pair of 1 is not complete
return set([Tile(group, '1')])
return (elements.winds | set([Tile(group, x) for x in range(2, 10)])) \
- set([x.exposed for x in hand.tiles])
# pair of 1 is not complete
return set([Tile(group, '1')])
def rearrange(hand, rest):
melds = []
......@@ -1182,9 +1177,8 @@ class ThirteenOrphans(MJRule):
if not missing:
# if all 13 tiles are there, we need any one of them:
return elements.majors
else:
assert len(missing) == 1
return missing
assert len(missing) == 1
return missing
def shouldTry(hand, maxMissing=4):
# TODO: look at how many tiles there still are on the wall
......
......@@ -56,8 +56,7 @@ class RuleTreeItem(TreeItem):
"""can be different for every rule"""
if hasattr(self, 'colCount'):
return self.colCount # pylint: disable=no-member
else:
return len(self.rawContent)
return len(self.rawContent)
def ruleset(self):
"""returns the ruleset containing this item"""
......@@ -141,8 +140,7 @@ class RuleItem(RuleTreeItem):
if self.rawContent.description:
return '<b>' + i18n(ruleset.name) + '</b><br><br>' + \
i18n(self.rawContent.description)
else:
return i18n(ruleset.name)
return i18n(ruleset.name)
class RuleModel(TreeModel):
......@@ -234,8 +232,7 @@ class RuleModel(TreeModel):
result = self.rootItem.content(section)
if result == 'doubles':
return 'x2'
else:
return i18nc('kajongg', result)
return i18nc('kajongg', result)
elif role == Qt.TextAlignmentRole:
leftRight = Qt.AlignLeft if section == 0 else Qt.AlignRight
return int(leftRight | Qt.AlignVCenter)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment