Commit 0a2a3555 authored by Wolfgang Rohdewald's avatar Wolfgang Rohdewald
Browse files

pylint: diverse cleanups

parent b86340cd
......@@ -42,6 +42,8 @@ except ImportError:
# pylint: disable=invalid-name
Internal = None
if os.name == 'nt':
# This is only needed for manual execution, and
# we expect python to be the python3 interpreter.
......@@ -216,7 +218,7 @@ Options {stropt} take a string argument like {example}.
if len(parts) == 1:
value = True
else:
value = ':'.join(parts[1:]) # pylint: disable=redefined-variable-type
value = ':'.join(parts[1:])
if option not in Debug.__dict__:
return '--debug: unknown option %s' % option
if not isinstance(Debug.__dict__[option], type(value)):
......@@ -336,7 +338,7 @@ class __Internal:
def __init__(self):
"""init the loggers"""
global Internal
global Internal # pylint: disable=global-statement
Internal = self
logName = os.path.basename(sys.argv[0]).replace('.py', '').replace('.exe', '') + '.log'
self.logger = logging.getLogger(logName)
......@@ -349,7 +351,6 @@ class __Internal:
except (AttributeError, socket.error):
haveDevLog = False
if not haveDevLog:
# pylint: disable=redefined-variable-type
logName = os.path.join(appdataDir(), logName)
print('Logging into {}'.format(logName))
handler = logging.handlers.RotatingFileHandler(
......
......@@ -869,8 +869,8 @@ class PlayingGame(Game):
self.prevActivePlayer.hidePopup()
self.__activePlayer = player
if Internal.scene: # mark the name of the active player in blue
for player in self.players:
player.colorizeName()
for _ in self.players:
_.colorizeName()
def prepareHand(self):
"""prepares the next hand"""
......
......@@ -98,7 +98,7 @@ class GamesModel(QAbstractTableModel):
"""for the two visible columns"""
# pylint: disable=no-self-use
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return (i18n("Started"), i18n("Players"))[section - 1]
return i18n('Players') if section == 2 else i18n('Started')
class Games(QDialog):
......
......@@ -161,6 +161,7 @@ class AIDefault:
@staticmethod
def weighSpecialGames(unusedAiInstance, candidates):
"""like color game, many dragons, many winds"""
# pylint: disable=too-many-nested-blocks
for candidate in candidates:
tile = candidate.tile
groupCount = candidates.groupCounts[tile.group]
......
......@@ -1005,10 +1005,10 @@ class KSwitchLanguageDialog(KDialog):
def restoreDefaults(self):
"""reset values to default"""
keys = list(x for x in self.languageRows.keys() if isinstance(x, KLanguageButton))
keys = list(x for x in self.languageRows if isinstance(x, KLanguageButton))
for _ in keys:
self.removeLanguage(_)
for removeButton in self.languageRows.keys():
for removeButton in self.languageRows:
if isAlive(removeButton):
removeButton.deleteLater()
self.languageRows = dict()
......
......@@ -836,19 +836,20 @@ def __scanSelf():
generate a class variable Message.msg where msg is the name (without spaces)
of the message. Example: 'Message.NoClaim'.
Those will be used as stateless constants. Also add them to dict Message.defined, but with spaces."""
if not Message.defined:
for glob in globals().values():
if hasattr(glob, "__mro__"):
if glob.__mro__[-2] == Message and len(glob.__mro__) > 2:
if glob.__name__.startswith('Message'):
try:
msg = glob()
except Exception:
logDebug('cannot instantiate %s' % glob.__name__)
raise
type.__setattr__(
Message, msg.name.replace(' ', ''), msg)
Message.defined[msg.name] = msg
if Message.defined:
return
for glob in globals().values():
if hasattr(glob, "__mro__"):
if glob.__mro__[-2] == Message and len(glob.__mro__) > 2:
if glob.__name__.startswith('Message'):
try:
msg = glob()
except Exception:
logDebug('cannot instantiate %s' % glob.__name__)
raise
type.__setattr__(
Message, msg.name.replace(' ', ''), msg)
Message.defined[msg.name] = msg
class ChatMessage(StrMixin):
......
......@@ -189,20 +189,17 @@ class MLocale:
for language in languages:
for context in ('kajongg', 'libkmahjongg5', 'kxmlgui5', 'kconfigwidgets5', 'libc'):
directories = cls.localeDirectories()
if Debug.i18n:
Internal.logger.debug('Searching translations in {}'.format(' '.join(directories)))
for resourceDir in directories:
try:
cls.translation.add_fallback(gettext.translation(
context, resourceDir, languages=[language]))
if Debug.i18n:
Internal.logger.debug('Found {} translation for {} in {}'.format(
language, context, resourceDir))
Internal.logger.debug(
'Found %s translation for %s in %s', language, context, resourceDir)
break
except IOError as e:
except IOError as _:
if Debug.i18n:
Internal.logger.debug(str(e))
pass
Internal.logger.debug(str(_))
cls.translation.install()
@staticmethod
......@@ -213,7 +210,7 @@ class MLocale:
os.path.join(os.path.dirname(sys.argv[0]), 'share/locale'))
result = list(x for x in candidates if os.path.exists(x))
if not result and Debug.i18n:
Internal.logger.debug('no locale path found. We have:{}'.format(os.listdir('.')))
Internal.logger.debug('no locale path found. We have:%s', os.listdir('.'))
if LOCALEPATH and os.path.exists(LOCALEPATH):
result.insert(0, LOCALEPATH)
......@@ -229,26 +226,42 @@ class MLocale:
if '_' in lang:
yield lang.split('_')[0]
@classmethod
def availableLanguages(cls):
"""see python lib, getdefaultlocale (which only returns the first one)"""
localenames = [getdefaultlocale()[0]]
@staticmethod
def get_localenames():
"""parse environment variables"""
result = []
defaultlocale = getdefaultlocale()[0]
if defaultlocale:
result.append(defaultlocale)
for variable in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
try:
localename = os.environ[variable]
if localename is None:
print(variable, 'is None')
except KeyError:
continue
else:
if variable == 'LANGUAGE':
localenames.extend(localename.split(':'))
result.extend(localename.split(':'))
else:
localenames.append(localename)
result.append(localename)
if Debug.i18n:
Internal.logger.debug('localenames: {}'.format(','.join(localenames)))
languages = list(_parse_localename(x)[0]
for x in localenames if len(x))
Internal.logger.debug('get_localenames: %s', format(','.join(result)))
return result
@classmethod
def availableLanguages(cls):
"""see python lib, getdefaultlocale (which only returns the first one)"""
localenames = cls.get_localenames()
languages = list()
for _ in localenames:
if _ is None:
continue
_ = _parse_localename(_)
if _[0]:
languages.append(_[0])
if Debug.i18n:
Internal.logger.debug('languages: {}'.format(','.join(languages)))
Internal.logger.debug('languages: %s', ','.join(languages) if languages else None)
for resourceDir in cls.localeDirectories():
for sysLanguage in sorted(os.listdir(resourceDir)):
if cls.__isLanguageInstalledForKajongg(sysLanguage):
......@@ -260,7 +273,7 @@ class MLocale:
if 'en_US' not in languages:
languages.extend(['en_US', 'en'])
if Debug.i18n:
Internal.logger.debug('languages available: {}'.format(':'.join(languages)))
Internal.logger.debug('languages available: %s', ':'.join(languages) if languages else None)
return ':'.join(languages)
@classmethod
......@@ -287,10 +300,12 @@ class MLocale:
_ = os.path.join(directory, lang, 'LC_MESSAGES', 'kajongg.mo')
if os.path.exists(_):
if Debug.i18n:
Internal.logger.debug('language {} installed in {}'.format(lang, _))
Internal.logger.debug('language %s installed in %s', lang, _)
return True
if Debug.i18n:
Internal.logger.debug('I am in {}. language {} not installed in {}'.format(os.getcwd(), lang, ','.join(cls.localeDirectories())))
Internal.logger.debug(
'I am in %s. language %s not installed in %s',
os.getcwd(), lang, ','.join(cls.localeDirectories()))
return False
MLocale.initStatic()
......@@ -217,7 +217,7 @@ class RuleList(list):
rule.key(), self[rule.key()].definition, rule.name, rule.definition))
self[rule.key()] = rule
def createRule(self, name: str, definition: str='', **kwargs):
def createRule(self, name: str, definition: str = '', **kwargs):
"""shortcut for simpler definition of predefined rulesets"""
defParts = definition.split('||')
rule = None
......
......@@ -1333,7 +1333,7 @@ class BlessingOfEarth(RuleCode):
class LongHand(RuleCode):
def appliesToHand(hand):
return (not hand.won and hand.lenOffset > 0) or hand.lenOffset > 1
return hand.lenOffset > 0 if not hand.won else hand.lenOffset > 1
class FalseDiscardForMJ(RuleCode):
......
......@@ -175,7 +175,7 @@ class RuleModel(TreeModel):
def data(self, index, role): # pylint: disable=no-self-use
"""get data fom model"""
# pylint: disable=too-many-branches,redefined-variable-type
# pylint: disable=too-many-branches
# too many branches
result = None
if index.isValid():
......@@ -393,7 +393,7 @@ class RuleTreeView(QTreeView):
if self.btnRemove and self.btnCopy:
self.ruleModel = EditableRuleModel(rulesets, self.name)
else:
self.ruleModel = RuleModel(rulesets, self.name) # pylint: disable=redefined-variable-type
self.ruleModel = RuleModel(rulesets, self.name)
self.setItemDelegateForColumn(
1,
RightAlignedCheckboxDelegate(
......
......@@ -244,8 +244,8 @@ class ScoringHandBoard(HandBoard):
if not newMeld:
return False
uiMeld = senderBoard.assignUITiles(uiTile, newMeld)
for uiTile, tile in zip(uiMeld, newMeld):
uiTile.tile = tile
for uitile, tile in zip(uiMeld, newMeld):
uitile.tile = tile
self.dropMeld(uiMeld)
def dropMeld(self, uiMeld):
......
......@@ -42,5 +42,3 @@ def srvMessage(*args):
def srvError(cls, *args):
"""raise an exception, passing args as a single string"""
raise cls(srvMessage(*args))
......@@ -52,6 +52,7 @@ class StateSaver(QObject):
@staticmethod
def __restore(widget, name):
"""decode the saved string"""
# pylint: disable=unsubscriptable-object
state = QByteArray.fromHex(Internal.Preferences[name].encode())
if state:
if name.endswith('State'):
......@@ -115,6 +116,7 @@ class StateSaver(QObject):
"""writes the state into Preferences, but does not save"""
for name, widget in self.widgets:
if isAlive(widget):
# pylint: disable=unsupported-assignment-operation
if hasattr(widget, 'saveState'):
Internal.Preferences[name + 'State'] = self.stateStr(widget.saveState())
if hasattr(widget, 'saveGeometry'):
......
......@@ -88,7 +88,7 @@ class TablesModel(QAbstractTableModel):
def data(self, index, role=Qt.DisplayRole):
"""score table"""
# pylint: disable=too-many-branches,too-many-locals,redefined-variable-type
# pylint: disable=too-many-branches,too-many-locals
result = None
if role == Qt.TextAlignmentRole:
if index.column() == 0:
......
......@@ -273,9 +273,9 @@ class UITile(AnimatedMixin, QGraphicsObject, StrMixin):
if sorter == Qt.Key_Down:
return self.xoffset * 100 + self.yoffset
elif sorter == Qt.Key_Up:
return -self.xoffset * 100 - self.yoffset
return -(self.xoffset * 100 + self.yoffset)
elif sorter == Qt.Key_Left:
return -self.yoffset * 100 - self.xoffset
return -(self.yoffset * 100 + self.xoffset)
return self.yoffset * 100 + self.xoffset
def setBoard(self, board, xoffset=None, yoffset=None, level=0):
......
......@@ -146,5 +146,3 @@ class User(pb.Avatar, StrMixin):
def __str__(self):
return self.name
......@@ -40,7 +40,7 @@ try:
except AttributeError:
STDOUTENCODING = None
if not STDOUTENCODING:
STDOUTENCODING = getpreferredencoding() # pylint: disable=redefined-variable-type
STDOUTENCODING = getpreferredencoding()
def stack(msg, limit=6):
......
......@@ -135,4 +135,3 @@ East = _East()
South = _South()
West = _West()
North = _North()
Supports Markdown
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