Skip to content

Commit 4fdf8e9

Browse files
authored
perf: Enable flake8 type checks (ApeWorX#2352)
1 parent 46a1d2c commit 4fdf8e9

Some content is hidden

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

54 files changed

+519
-405
lines changed

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ repos:
1919
rev: 7.1.1
2020
hooks:
2121
- id: flake8
22-
additional_dependencies: [flake8-breakpoint, flake8-print, flake8-pydantic]
22+
additional_dependencies: [flake8-breakpoint, flake8-print, flake8-pydantic, flake8-type-checking]
2323

2424
- repo: https://github.com/pre-commit/mirrors-mypy
2525
rev: v1.13.0

setup.cfg

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,13 @@ exclude =
77
build
88
.eggs
99
tests/integration/cli/projects
10-
ignore = E704,W503,PYD002
10+
ignore = E704,W503,PYD002,TC003,TC006
1111
per-file-ignores =
1212
# Need signal handler before imports
1313
src/ape/__init__.py: E402
1414
# Test data causes long lines
1515
tests/functional/data/python/__init__.py: E501
1616
tests/functional/utils/expected_traces.py: E501
17+
18+
type-checking-pydantic-enabled = True
19+
type-checking-sqlalchemy-enabled = True

setup.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
"flake8-breakpoint>=1.1.0,<2", # Detect breakpoints left in code
3535
"flake8-print>=4.0.1,<5", # Detect print statements left in code
3636
"flake8-pydantic", # For detecting issues with Pydantic models
37+
"flake8-type-checking", # Detect imports to move in/out of type-checking blocks
3738
"isort>=5.13.2,<6", # Import sorting linter
3839
"mdformat>=0.7.18", # Auto-formatter for markdown
3940
"mdformat-gfm>=0.3.5", # Needed for formatting GitHub-flavored markdown

src/ape/_cli.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,20 @@
77
from importlib import import_module
88
from importlib.metadata import entry_points
99
from pathlib import Path
10-
from typing import Any, Optional
10+
from typing import TYPE_CHECKING, Any, Optional
1111
from warnings import catch_warnings, simplefilter
1212

1313
import click
1414
import rich
1515
import yaml
16-
from click import Context
1716

1817
from ape.cli.options import ape_cli_context
1918
from ape.exceptions import Abort, ApeException, ConfigError, handle_ape_exception
2019
from ape.logging import logger
2120

21+
if TYPE_CHECKING:
22+
from click import Context
23+
2224
_DIFFLIB_CUT_OFF = 0.6
2325

2426

@@ -53,7 +55,7 @@ def _validate_config():
5355
class ApeCLI(click.MultiCommand):
5456
_CLI_GROUP_NAME = "ape_cli_subcommands"
5557

56-
def parse_args(self, ctx: Context, args: list[str]) -> list[str]:
58+
def parse_args(self, ctx: "Context", args: list[str]) -> list[str]:
5759
# Validate the config before any argument parsing,
5860
# as arguments may utilize config.
5961
if "--help" not in args and args != []:

src/ape/api/accounts.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
from eip712.messages import SignableMessage as EIP712SignableMessage
1111
from eth_account import Account
1212
from eth_account.messages import encode_defunct
13-
from eth_pydantic_types import HexBytes
1413
from eth_utils import to_hex
1514
from ethpm_types import ContractType
1615

@@ -31,6 +30,8 @@
3130
from ape.utils.misc import raises_not_implemented
3231

3332
if TYPE_CHECKING:
33+
from eth_pydantic_types import HexBytes
34+
3435
from ape.contracts import ContractContainer, ContractInstance
3536

3637

@@ -65,7 +66,7 @@ def alias(self) -> Optional[str]:
6566
"""
6667
return None
6768

68-
def sign_raw_msghash(self, msghash: HexBytes) -> Optional[MessageSignature]:
69+
def sign_raw_msghash(self, msghash: "HexBytes") -> Optional[MessageSignature]:
6970
"""
7071
Sign a raw message hash.
7172

src/ape/api/address.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,13 @@
77
from ape.exceptions import ConversionError
88
from ape.types.address import AddressType
99
from ape.types.units import CurrencyValue
10-
from ape.types.vm import ContractCode
1110
from ape.utils.basemodel import BaseInterface
1211
from ape.utils.misc import log_instead_of_fail
1312

1413
if TYPE_CHECKING:
1514
from ape.api.transactions import ReceiptAPI, TransactionAPI
1615
from ape.managers.chain import AccountHistory
16+
from ape.types.vm import ContractCode
1717

1818

1919
class BaseAddress(BaseInterface):
@@ -146,7 +146,7 @@ def __setattr__(self, attr: str, value: Any) -> None:
146146
super().__setattr__(attr, value)
147147

148148
@property
149-
def code(self) -> ContractCode:
149+
def code(self) -> "ContractCode":
150150
"""
151151
The raw bytes of the smart-contract code at the address.
152152
"""

src/ape/api/compiler.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,21 @@
44
from pathlib import Path
55
from typing import TYPE_CHECKING, Optional
66

7-
from eth_pydantic_types import HexBytes
8-
from ethpm_types import ContractType
9-
from ethpm_types.source import Content, ContractSource
10-
from packaging.version import Version
11-
12-
from ape.api.config import PluginConfig
13-
from ape.api.trace import TraceAPI
147
from ape.exceptions import APINotImplementedError, ContractLogicError
15-
from ape.types.coverage import ContractSourceCoverage
16-
from ape.types.trace import SourceTraceback
178
from ape.utils.basemodel import BaseInterfaceModel
189
from ape.utils.misc import log_instead_of_fail, raises_not_implemented
1910

2011
if TYPE_CHECKING:
12+
from eth_pydantic_types import HexBytes
13+
from ethpm_types import ContractType
14+
from ethpm_types.source import Content, ContractSource
15+
from packaging.version import Version
16+
17+
from ape.api.config import PluginConfig
18+
from ape.api.trace import TraceAPI
2119
from ape.managers.project import ProjectManager
20+
from ape.types.coverage import ContractSourceCoverage
21+
from ape.types.trace import SourceTraceback
2222

2323

2424
class CompilerAPI(BaseInterfaceModel):
@@ -44,7 +44,7 @@ def name(self) -> str:
4444
The name of the compiler.
4545
"""
4646

47-
def get_config(self, project: Optional["ProjectManager"] = None) -> PluginConfig:
47+
def get_config(self, project: Optional["ProjectManager"] = None) -> "PluginConfig":
4848
"""
4949
The combination of settings from ``ape-config.yaml`` and ``.compiler_settings``.
5050
@@ -79,7 +79,7 @@ def get_compiler_settings( # type: ignore[empty-body]
7979
contract_filepaths: Iterable[Path],
8080
project: Optional["ProjectManager"] = None,
8181
**overrides,
82-
) -> dict[Version, dict]:
82+
) -> dict["Version", dict]:
8383
"""
8484
Get a mapping of the settings that would be used to compile each of the sources
8585
by the compiler version number.
@@ -101,7 +101,7 @@ def compile(
101101
contract_filepaths: Iterable[Path],
102102
project: Optional["ProjectManager"],
103103
settings: Optional[dict] = None,
104-
) -> Iterator[ContractType]:
104+
) -> Iterator["ContractType"]:
105105
"""
106106
Compile the given source files. All compiler plugins must implement this function.
107107
@@ -123,7 +123,7 @@ def compile_code( # type: ignore[empty-body]
123123
project: Optional["ProjectManager"],
124124
settings: Optional[dict] = None,
125125
**kwargs,
126-
) -> ContractType:
126+
) -> "ContractType":
127127
"""
128128
Compile a program.
129129
@@ -162,7 +162,7 @@ def get_version_map( # type: ignore[empty-body]
162162
self,
163163
contract_filepaths: Iterable[Path],
164164
project: Optional["ProjectManager"] = None,
165-
) -> dict[Version, set[Path]]:
165+
) -> dict["Version", set[Path]]:
166166
"""
167167
Get a map of versions to source paths.
168168
@@ -218,8 +218,8 @@ def enrich_error(self, err: ContractLogicError) -> ContractLogicError:
218218

219219
@raises_not_implemented
220220
def trace_source( # type: ignore[empty-body]
221-
self, contract_source: ContractSource, trace: TraceAPI, calldata: HexBytes
222-
) -> SourceTraceback:
221+
self, contract_source: "ContractSource", trace: "TraceAPI", calldata: "HexBytes"
222+
) -> "SourceTraceback":
223223
"""
224224
Get a source-traceback for the given contract type.
225225
The source traceback object contains all the control paths taken in the transaction.
@@ -239,7 +239,7 @@ def trace_source( # type: ignore[empty-body]
239239
@raises_not_implemented
240240
def flatten_contract( # type: ignore[empty-body]
241241
self, path: Path, project: Optional["ProjectManager"] = None, **kwargs
242-
) -> Content:
242+
) -> "Content":
243243
"""
244244
Get the content of a flattened contract via its source path.
245245
Plugin implementations handle import resolution, SPDX de-duplication,
@@ -259,7 +259,7 @@ def flatten_contract( # type: ignore[empty-body]
259259

260260
@raises_not_implemented
261261
def init_coverage_profile(
262-
self, source_coverage: ContractSourceCoverage, contract_source: ContractSource
262+
self, source_coverage: "ContractSourceCoverage", contract_source: "ContractSource"
263263
): # type: ignore[empty-body]
264264
"""
265265
Initialize an empty report for the given source ID. Modifies the given source

src/ape/api/explorers.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
from abc import abstractmethod
2-
from typing import Optional
3-
4-
from ethpm_types import ContractType
2+
from typing import TYPE_CHECKING, Optional
53

64
from ape.api.networks import NetworkAPI
7-
from ape.types.address import AddressType
85
from ape.utils.basemodel import BaseInterfaceModel
96

7+
if TYPE_CHECKING:
8+
from ethpm_types import ContractType
9+
10+
from ape.types.address import AddressType
11+
1012

1113
class ExplorerAPI(BaseInterfaceModel):
1214
"""
@@ -18,7 +20,7 @@ class ExplorerAPI(BaseInterfaceModel):
1820
network: NetworkAPI
1921

2022
@abstractmethod
21-
def get_address_url(self, address: AddressType) -> str:
23+
def get_address_url(self, address: "AddressType") -> str:
2224
"""
2325
Get an address URL, such as for a transaction.
2426
@@ -42,7 +44,7 @@ def get_transaction_url(self, transaction_hash: str) -> str:
4244
"""
4345

4446
@abstractmethod
45-
def get_contract_type(self, address: AddressType) -> Optional[ContractType]:
47+
def get_contract_type(self, address: "AddressType") -> Optional["ContractType"]:
4648
"""
4749
Get the contract type for a given address if it has been published to this explorer.
4850
@@ -54,7 +56,7 @@ def get_contract_type(self, address: AddressType) -> Optional[ContractType]:
5456
"""
5557

5658
@abstractmethod
57-
def publish_contract(self, address: AddressType):
59+
def publish_contract(self, address: "AddressType"):
5860
"""
5961
Publish a contract to the explorer.
6062

0 commit comments

Comments
 (0)