Skip to content

Commit 144e1e2

Browse files
authored
Fix pylint (microsoft#888)
* add_pylint_to_workflow * fix-pylint * fix_pylinterror * fix-issue
1 parent 635632e commit 144e1e2

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

103 files changed

+311
-380
lines changed

.github/workflows/test.yml

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,37 @@ jobs:
3333
- name: Install Qlib with pip
3434
run: |
3535
pip install numpy==1.19.5 ruamel.yaml
36-
pip install pyqlib --ignore-installed
36+
pip install pyqlib --ignore-installed
37+
38+
# Check Qlib with pylint
39+
# TODO: These problems we will solve in the future. Important among them are: W0221, W0223, W0237, E1102
40+
# C0103: invalid-name
41+
# C0209: consider-using-f-string
42+
# R0402: consider-using-from-import
43+
# R1705: no-else-return
44+
# R1710: inconsistent-return-statements
45+
# R1725: super-with-arguments
46+
# R1735: use-dict-literal
47+
# W0102: dangerous-default-value
48+
# W0212: protected-access
49+
# W0221: arguments-differ
50+
# W0223: abstract-method
51+
# W0231: super-init-not-called
52+
# W0237: arguments-renamed
53+
# W0612: unused-variable
54+
# W0621: redefined-outer-name
55+
# W0622: redefined-builtin
56+
# FIXME: specify exception type
57+
# W0703: broad-except
58+
# W1309: f-string-without-interpolation
59+
# E1102: not-callable
60+
# E1136: unsubscriptable-object
61+
# References for parameters: https://github.com/PyCQA/pylint/issues/4577#issuecomment-1000245962
62+
- name: Check Qlib with pylint
63+
run: |
64+
pip install --upgrade pip
65+
pip install pylint
66+
pylint --disable=C0104,C0114,C0115,C0116,C0301,C0302,C0411,C0413,C1802,R0201,R0401,R0801,R0902,R0903,R0911,R0912,R0913,R0914,R0915,R1720,W0105,W0123,W0201,W0511,W0613,W1113,W1514,E0401,E1121,C0103,C0209,R0402,R1705,R1710,R1725,R1735,W0102,W0212,W0221,W0223,W0231,W0237,W0612,W0621,W0622,W0703,W1309,E1102,E1136 --const-rgx='[a-z_][a-z0-9_]{2,30}$' qlib --init-hook "import astroid; astroid.context.InferenceContext.max_inferred = 500"
3767
3868
- name: Test data downloads
3969
run: |

qlib/__init__.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@ def init(default_conf="client", **kwargs):
3030
When using the recorder, skip_if_reg can set to True to avoid loss of recorder.
3131
3232
"""
33-
from .config import C
34-
from .data.cache import H
33+
from .config import C # pylint: disable=C0415
34+
from .data.cache import H # pylint: disable=C0415
3535

3636
# FIXME: this logger ignored the level in config
3737
logger = get_module_logger("Initialization", level=logging.INFO)
@@ -85,7 +85,7 @@ def _mount_nfs_uri(provider_uri, mount_path, auto_mount: bool = False):
8585
mount_command = "sudo mount.nfs %s %s" % (provider_uri, mount_path)
8686
# If the provider uri looks like this 172.23.233.89//data/csdesign'
8787
# It will be a nfs path. The client provider will be used
88-
if not auto_mount:
88+
if not auto_mount: # pylint: disable=R1702
8989
if not Path(mount_path).exists():
9090
raise FileNotFoundError(
9191
f"Invalid mount path: {mount_path}! Please mount manually: {mount_command} or Set init parameter `auto_mount=True`"
@@ -139,8 +139,10 @@ def _mount_nfs_uri(provider_uri, mount_path, auto_mount: bool = False):
139139
if not _is_mount:
140140
try:
141141
Path(mount_path).mkdir(parents=True, exist_ok=True)
142-
except Exception:
143-
raise OSError(f"Failed to create directory {mount_path}, please create {mount_path} manually!")
142+
except Exception as e:
143+
raise OSError(
144+
f"Failed to create directory {mount_path}, please create {mount_path} manually!"
145+
) from e
144146

145147
# check nfs-common
146148
command_res = os.popen("dpkg -l | grep nfs-common")

qlib/backtest/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,8 +171,8 @@ def get_strategy_executor(
171171
# NOTE:
172172
# - for avoiding recursive import
173173
# - typing annotations is not reliable
174-
from ..strategy.base import BaseStrategy
175-
from .executor import BaseExecutor
174+
from ..strategy.base import BaseStrategy # pylint: disable=C0415
175+
from .executor import BaseExecutor # pylint: disable=C0415
176176

177177
trade_account = create_account_instance(
178178
start_time=start_time, end_time=end_time, benchmark=benchmark, account=account, pos_type=pos_type

qlib/backtest/account.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@
22
# Licensed under the MIT License.
33
from __future__ import annotations
44
import copy
5-
from typing import Dict, List, Tuple, TYPE_CHECKING
5+
from typing import Dict, List, Tuple
66
from qlib.utils import init_instance_by_config
77
import pandas as pd
88

9-
from .position import BasePosition, InfPosition, Position
9+
from .position import BasePosition
1010
from .report import PortfolioMetrics, Indicator
1111
from .decision import BaseTradeDecision, Order
1212
from .exchange import Exchange

qlib/backtest/decision.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,18 @@
77
from qlib.utils.time import concat_date_time, epsilon_change
88
from qlib.log import get_module_logger
99

10+
from typing import ClassVar, Optional, Union, List, Tuple
11+
1012
# try to fix circular imports when enabling type hints
11-
from typing import Callable, TYPE_CHECKING
13+
from typing import TYPE_CHECKING
1214

1315
if TYPE_CHECKING:
1416
from qlib.strategy.base import BaseStrategy
1517
from qlib.backtest.exchange import Exchange
1618
from qlib.backtest.utils import TradeCalendarManager
17-
import warnings
1819
import numpy as np
1920
import pandas as pd
20-
import numpy as np
21-
from dataclasses import dataclass, field
22-
from typing import ClassVar, Optional, Union, List, Set, Tuple
21+
from dataclasses import dataclass
2322

2423

2524
class OrderDir(IntEnum):
@@ -418,7 +417,7 @@ def get_range_limit(self, **kwargs) -> Tuple[int, int]:
418417
return kwargs["default_value"]
419418
else:
420419
# Default to get full index
421-
raise NotImplementedError(f"The decision didn't provide an index range")
420+
raise NotImplementedError(f"The decision didn't provide an index range") from NotImplementedError
422421

423422
# clip index
424423
if getattr(self, "total_step", None) is not None:

qlib/backtest/exchange.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@
33
from __future__ import annotations
44
from collections import defaultdict
55
from typing import TYPE_CHECKING
6+
from typing import List, Tuple, Union
67

78
if TYPE_CHECKING:
89
from .account import Account
910

1011
from qlib.backtest.position import BasePosition, Position
1112
import random
12-
from typing import List, Tuple, Union
1313
import numpy as np
1414
import pandas as pd
1515

@@ -18,7 +18,7 @@
1818
from ..constant import REG_CN
1919
from ..log import get_module_logger
2020
from .decision import Order, OrderDir, OrderHelper
21-
from .high_performance_ds import BaseQuote, PandasQuote, NumpyQuote
21+
from .high_performance_ds import BaseQuote, NumpyQuote
2222

2323

2424
class Exchange:

qlib/backtest/executor.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,18 @@
1-
from abc import abstractclassmethod, abstractmethod
1+
from abc import abstractmethod
22
import copy
33
from qlib.backtest.position import BasePosition
44
from qlib.log import get_module_logger
55
from types import GeneratorType
66
from qlib.backtest.account import Account
7-
import warnings
87
import pandas as pd
98
from typing import List, Tuple, Union
109
from collections import defaultdict
1110

12-
from qlib.backtest.report import Indicator
13-
14-
from .decision import EmptyTradeDecision, Order, BaseTradeDecision
11+
from .decision import Order, BaseTradeDecision
1512
from .exchange import Exchange
1613
from .utils import TradeCalendarManager, CommonInfrastructure, LevelInfrastructure, get_start_end_idx
1714

1815
from ..utils import init_instance_by_config
19-
from ..utils.time import Freq
2016
from ..strategy.base import BaseStrategy
2117

2218

@@ -193,7 +189,8 @@ def execute(self, trade_decision: BaseTradeDecision, level: int = 0):
193189
pass
194190
return return_value.get("execute_result")
195191

196-
@abstractclassmethod
192+
@classmethod
193+
@abstractmethod
197194
def _collect_data(cls, trade_decision: BaseTradeDecision, level: int = 0) -> Tuple[List[object], dict]:
198195
"""
199196
Please refer to the doc of collect_data
@@ -453,7 +450,6 @@ def post_inner_exe_step(self, inner_exe_res):
453450
inner_exe_res :
454451
the execution result of inner task
455452
"""
456-
pass
457453

458454
def get_all_executors(self):
459455
"""get all executors, including self and inner_executor.get_all_executors()"""

qlib/backtest/position.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
# Licensed under the MIT License.
33

44

5-
import copy
6-
import pathlib
75
from typing import Dict, List, Union
86

97
import pandas as pd
@@ -538,7 +536,7 @@ def get_cash(self, include_settle=False) -> float:
538536
def get_stock_amount_dict(self) -> Dict:
539537
raise NotImplementedError(f"InfPosition doesn't support get_stock_amount_dict")
540538

541-
def get_stock_weight_dict(self, only_stock: bool) -> Dict:
539+
def get_stock_weight_dict(self, only_stock: bool = False) -> Dict:
542540
raise NotImplementedError(f"InfPosition doesn't support get_stock_weight_dict")
543541

544542
def add_count_all(self, bar):

qlib/backtest/report.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,8 @@
1010
import pandas as pd
1111

1212
from qlib.backtest.exchange import Exchange
13-
from .decision import IdxTradeRange
1413
from qlib.backtest.decision import BaseTradeDecision, Order, OrderDir
15-
from qlib.backtest.utils import TradeCalendarManager
16-
from .high_performance_ds import BaseOrderIndicator, PandasOrderIndicator, NumpyOrderIndicator, SingleMetric
17-
from ..data import D
14+
from .high_performance_ds import BaseOrderIndicator, NumpyOrderIndicator, SingleMetric
1815
from ..tests.config import CSI300_BENCH
1916
from ..utils.resam import get_higher_eq_freq_feature, resam_ts_data
2017
import qlib.utils.index_data as idd

qlib/config.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -388,13 +388,11 @@ def set(self, default_conf: str = "client", **kwargs):
388388
default_conf : str
389389
the default config template chosen by user: "server", "client"
390390
"""
391-
from .utils import set_log_with_config, get_module_logger, can_use_cache
391+
from .utils import set_log_with_config, get_module_logger, can_use_cache # pylint: disable=C0415
392392

393393
self.reset()
394394

395-
_logging_config = self.logging_config
396-
if "logging_config" in kwargs:
397-
_logging_config = kwargs["logging_config"]
395+
_logging_config = kwargs.get("logging_config", self.logging_config)
398396

399397
# set global config
400398
if _logging_config:
@@ -433,11 +431,11 @@ def set(self, default_conf: str = "client", **kwargs):
433431
)
434432

435433
def register(self):
436-
from .utils import init_instance_by_config
437-
from .data.ops import register_all_ops
438-
from .data.data import register_all_wrappers
439-
from .workflow import R, QlibRecorder
440-
from .workflow.utils import experiment_exit_handler
434+
from .utils import init_instance_by_config # pylint: disable=C0415
435+
from .data.ops import register_all_ops # pylint: disable=C0415
436+
from .data.data import register_all_wrappers # pylint: disable=C0415
437+
from .workflow import R, QlibRecorder # pylint: disable=C0415
438+
from .workflow.utils import experiment_exit_handler # pylint: disable=C0415
441439

442440
register_all_ops(self)
443441
register_all_wrappers(self)
@@ -454,7 +452,7 @@ def register(self):
454452
self._registered = True
455453

456454
def reset_qlib_version(self):
457-
import qlib
455+
import qlib # pylint: disable=C0415
458456

459457
reset_version = self.get("qlib_reset_version", None)
460458
if reset_version is not None:

0 commit comments

Comments
 (0)