Skip to content

Commit c405205

Browse files
authored
Switch to using modern Python union syntax (#1286)
1 parent c123eb9 commit c405205

Some content is hidden

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

43 files changed

+536
-546
lines changed

src/basilisp/cli.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@
66
import sys
77
import textwrap
88
import types
9-
from collections.abc import Sequence
9+
from collections.abc import Callable, Sequence
1010
from pathlib import Path
11-
from typing import Any, Callable, Optional, Union
11+
from typing import Any, Union
1212

1313
from basilisp import main as basilisp
1414
from basilisp.lang import compiler as compiler
@@ -97,7 +97,7 @@ def prepend_once(path: str) -> None:
9797
prepend_once(unsafe_path)
9898

9999

100-
def _to_bool(v: Optional[str]) -> Optional[bool]:
100+
def _to_bool(v: str | None) -> bool | None:
101101
"""Coerce a string argument to a boolean value, if possible."""
102102
if v is None:
103103
return v
@@ -389,8 +389,8 @@ def _add_runtime_arg_group(parser: argparse.ArgumentParser) -> None:
389389
def _subcommand(
390390
subcommand: str,
391391
*,
392-
help: Optional[str] = None, # pylint: disable=redefined-builtin
393-
description: Optional[str] = None,
392+
help: str | None = None, # pylint: disable=redefined-builtin
393+
description: str | None = None,
394394
handler: Handler,
395395
allows_extra: bool = False,
396396
) -> Callable[
@@ -820,7 +820,7 @@ def run_script():
820820
os.execvp("basilisp", args) # nosec B606, B607
821821

822822

823-
def invoke_cli(args: Optional[Sequence[str]] = None) -> None:
823+
def invoke_cli(args: Sequence[str] | None = None) -> None:
824824
"""Entrypoint to run the Basilisp CLI."""
825825
parser = argparse.ArgumentParser(
826826
description="Basilisp is a Lisp dialect inspired by Clojure targeting Python 3."

src/basilisp/contrib/pytest/testrunner.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
import os
44
import sys
55
import traceback
6-
from collections.abc import Iterable, Iterator
6+
from collections.abc import Callable, Iterable, Iterator
77
from pathlib import Path
88
from types import GeneratorType
9-
from typing import Callable, Optional
9+
from typing import Optional
1010

1111
import pytest
1212

@@ -108,7 +108,7 @@ def __init__(self, fixtures: Iterable[FixtureFunction]):
108108
self._teardowns: Iterable[FixtureTeardown] = ()
109109

110110
@staticmethod
111-
def _run_fixture(fixture: FixtureFunction) -> Optional[Iterator[None]]:
111+
def _run_fixture(fixture: FixtureFunction) -> Iterator[None] | None:
112112
"""Run a fixture function. If the fixture is a generator function, return the
113113
generator/coroutine. Otherwise, simply return the value from the function, if
114114
one."""
@@ -199,7 +199,7 @@ class BasilispFile(pytest.File):
199199

200200
def __init__(self, **kwargs) -> None:
201201
super().__init__(**kwargs)
202-
self._fixture_manager: Optional[FixtureManager] = None
202+
self._fixture_manager: FixtureManager | None = None
203203

204204
@staticmethod
205205
def _collected_fixtures(
@@ -248,7 +248,7 @@ def _import_module(self) -> runtime.BasilispModule:
248248
modnames = _get_fully_qualified_module_names(self.path)
249249
assert modnames, "Must have at least one module name"
250250

251-
exc: Optional[ModuleNotFoundError] = None
251+
exc: ModuleNotFoundError | None = None
252252
for modname in modnames:
253253
try:
254254
module = importlib.import_module(modname)
@@ -360,7 +360,7 @@ def runtest(self):
360360
If any tests fail, raise an ExceptionInfo exception with the test failures.
361361
PyTest will invoke self.repr_failure to display the failures to the user."""
362362
results: lmap.PersistentMap = self._run_test()
363-
failures: Optional[vec.PersistentVector] = results.val_at(_FAILURES_KW)
363+
failures: vec.PersistentVector | None = results.val_at(_FAILURES_KW)
364364
if runtime.to_seq(failures):
365365
raise TestFailuresInfo("Test failures", lmap.map(results))
366366

@@ -391,7 +391,7 @@ def repr_failure(self, excinfo, style=None):
391391
def reportinfo(self):
392392
return self.fspath, 0, self.name
393393

394-
def _error_msg(self, exc: Exception, line: Optional[int] = None) -> str:
394+
def _error_msg(self, exc: Exception, line: int | None = None) -> str:
395395
line_msg = Maybe(line).map(lambda l: f":{l}").or_else_get("")
396396
messages = [f"ERROR in ({self.name}) ({self._filename}{line_msg})", "\n\n"]
397397
messages.extend(traceback.format_exception(Exception, exc, exc.__traceback__))

src/basilisp/contrib/sphinx/autodoc.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import logging
44
import sys
55
import types
6-
from typing import Any, Optional, cast
6+
from typing import Any, cast
77

88
from sphinx.ext.autodoc import (
99
ClassDocumenter,
@@ -51,7 +51,7 @@
5151
_METHODS_KW = kw.keyword("methods")
5252

5353

54-
def _get_doc(reference: IReference) -> Optional[list[list[str]]]:
54+
def _get_doc(reference: IReference) -> list[list[str]] | None:
5555
"""Return the docstring of an IReference type (e.g. Namespace or Var)."""
5656
docstring = reference.meta and reference.meta.val_at(_DOC_KW)
5757
if docstring is None:
@@ -79,7 +79,7 @@ class NamespaceDocumenter(Documenter):
7979
"deprecated": bool_option,
8080
}
8181

82-
object: Optional[runtime.Namespace]
82+
object: runtime.Namespace | None
8383

8484
@classmethod
8585
def can_document_member(
@@ -122,7 +122,7 @@ def import_object(self, raiseerror: bool = False) -> bool:
122122
self.module = ns.module
123123
return True
124124

125-
def get_doc(self) -> Optional[list[list[str]]]:
125+
def get_doc(self) -> list[list[str]] | None:
126126
assert self.object is not None
127127
return _get_doc(self.object)
128128

@@ -155,7 +155,7 @@ def filter_members(
155155
continue
156156
if val.meta is not None:
157157
# Ignore undocumented members unless undoc_members is set
158-
docstring: Optional[str] = val.meta.val_at(_DOC_KW)
158+
docstring: str | None = val.meta.val_at(_DOC_KW)
159159
if docstring is None and not self.options.undoc_members:
160160
continue
161161
# Private members will be excluded unless they are requested
@@ -215,7 +215,7 @@ class VarDocumenter(Documenter):
215215
"deprecated": bool_option,
216216
}
217217

218-
object: Optional[runtime.Var]
218+
object: runtime.Var | None
219219

220220
@classmethod
221221
def can_document_member(
@@ -292,7 +292,7 @@ def add_directive_header(self, sig: str) -> None:
292292
if self.object.meta.val_at(_DEPRECATED_KW):
293293
self.add_line(" :deprecated:", sourcename)
294294

295-
def get_doc(self) -> Optional[list[list[str]]]:
295+
def get_doc(self) -> list[list[str]] | None:
296296
assert self.object is not None
297297
return _get_doc(self.object)
298298

src/basilisp/contrib/sphinx/domain.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import logging
22
from collections import defaultdict
33
from collections.abc import Iterable
4-
from typing import Any, NamedTuple, Optional, Union, cast
4+
from typing import Any, NamedTuple, cast
55

66
from docutils import nodes
77
from docutils.nodes import Element, Node
@@ -316,7 +316,7 @@ class BasilispNamespaceIndex(Index):
316316
shortname = "namespaces"
317317

318318
def generate( # pylint: disable=too-many-locals
319-
self, docnames: Optional[Iterable[str]] = None
319+
self, docnames: Iterable[str] | None = None
320320
) -> tuple[list[tuple[str, list[IndexEntry]]], bool]:
321321
content: dict[str, list[IndexEntry]] = defaultdict(list)
322322

@@ -548,10 +548,10 @@ def resolve_xref( # pylint: disable=too-many-arguments
548548
target: str,
549549
node: pending_xref,
550550
contnode: Element,
551-
) -> Optional[Element]:
551+
) -> Element | None:
552552
nsname = node.get("lpy:namespace")
553553

554-
maybe_obj: Union[FormEntry, NamespaceEntry, VarEntry, None]
554+
maybe_obj: FormEntry | NamespaceEntry | VarEntry | None
555555
reftype = node.get("reftype")
556556
if reftype == "ns":
557557
maybe_obj = self.namespaces.get(target)

src/basilisp/importer.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from functools import lru_cache
1010
from importlib.abc import MetaPathFinder, SourceLoader
1111
from importlib.machinery import ModuleSpec
12-
from typing import Any, Optional, cast
12+
from typing import Any, cast
1313

1414
from typing_extensions import TypedDict
1515

@@ -144,9 +144,9 @@ def __init__(self):
144144
def find_spec(
145145
self,
146146
fullname: str,
147-
path: Optional[Sequence[str]],
148-
target: Optional[types.ModuleType] = None,
149-
) -> Optional[ModuleSpec]:
147+
path: Sequence[str] | None,
148+
target: types.ModuleType | None = None,
149+
) -> ModuleSpec | None:
150150
"""Find the ModuleSpec for the specified Basilisp module.
151151
152152
Returns None if the module is not a Basilisp module to allow import processing to continue.
@@ -234,7 +234,7 @@ def get_filename(self, fullname: str) -> str:
234234
assert spec is not None, "spec must be defined here"
235235
return spec.loader_state["filename"]
236236

237-
def get_code(self, fullname: str) -> Optional[types.CodeType]:
237+
def get_code(self, fullname: str) -> types.CodeType | None:
238238
"""Return code to load a Basilisp module.
239239
240240
This function is part of the ABC for `importlib.abc.ExecutionLoader` which is

src/basilisp/lang/atom.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import threading
2-
from typing import Callable, Generic, Optional, TypeVar
2+
from collections.abc import Callable
3+
from typing import Concatenate, Generic, TypeVar
34

4-
from typing_extensions import Concatenate, ParamSpec
5+
from typing_extensions import ParamSpec
56

67
from basilisp.lang import map as lmap
78
from basilisp.lang.interfaces import IPersistentMap, RefValidator
@@ -17,10 +18,10 @@ class Atom(RefBase[T], Generic[T]):
1718
def __init__(
1819
self,
1920
state: T,
20-
meta: Optional[IPersistentMap] = None,
21-
validator: Optional[RefValidator] = None,
21+
meta: IPersistentMap | None = None,
22+
validator: RefValidator | None = None,
2223
) -> None:
23-
self._meta: Optional[IPersistentMap] = meta
24+
self._meta: IPersistentMap | None = meta
2425
self._state = state
2526
self._lock = threading.RLock()
2627
self._watches = lmap.EMPTY

src/basilisp/lang/compiler/__init__.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
import os
44
import types
55
from ast import unparse
6-
from collections.abc import Iterable
6+
from collections.abc import Callable, Iterable
77
from pathlib import Path
8-
from typing import Any, Callable, Optional
8+
from typing import Any
99

1010
from basilisp.lang import list as llist
1111
from basilisp.lang import map as lmap
@@ -60,7 +60,7 @@ def to_py_str(t: ast.AST) -> str:
6060
class CompilerContext:
6161
__slots__ = ("_filename", "_actx", "_gctx", "_optimizer")
6262

63-
def __init__(self, filename: str, opts: Optional[CompilerOpts] = None):
63+
def __init__(self, filename: str, opts: CompilerOpts | None = None):
6464
self._filename = filename
6565
self._actx = AnalyzerContext(filename=filename, opts=opts)
6666
self._gctx = GeneratorContext(filename=filename, opts=opts)
@@ -84,15 +84,15 @@ def py_ast_optimizer(self) -> PythonASTOptimizer:
8484

8585

8686
def compiler_opts( # pylint: disable=too-many-arguments
87-
generate_auto_inlines: Optional[bool] = None,
88-
inline_functions: Optional[bool] = None,
89-
warn_on_arity_mismatch: Optional[bool] = None,
90-
warn_on_shadowed_name: Optional[bool] = None,
91-
warn_on_shadowed_var: Optional[bool] = None,
92-
warn_on_unused_names: Optional[bool] = None,
93-
warn_on_non_dynamic_set: Optional[bool] = None,
94-
use_var_indirection: Optional[bool] = None,
95-
warn_on_var_indirection: Optional[bool] = None,
87+
generate_auto_inlines: bool | None = None,
88+
inline_functions: bool | None = None,
89+
warn_on_arity_mismatch: bool | None = None,
90+
warn_on_shadowed_name: bool | None = None,
91+
warn_on_shadowed_var: bool | None = None,
92+
warn_on_unused_names: bool | None = None,
93+
warn_on_non_dynamic_set: bool | None = None,
94+
use_var_indirection: bool | None = None,
95+
warn_on_var_indirection: bool | None = None,
9696
) -> CompilerOpts:
9797
"""Return a map of compiler options with defaults applied."""
9898
return lmap.map(
@@ -148,7 +148,7 @@ def compile_and_exec_form(
148148
ctx: CompilerContext,
149149
ns: runtime.Namespace,
150150
wrapped_fn_name: str = _DEFAULT_FN,
151-
collect_bytecode: Optional[BytecodeCollector] = None,
151+
collect_bytecode: BytecodeCollector | None = None,
152152
) -> Any:
153153
"""Compile and execute the given form. This function will be most useful
154154
for the REPL and testing purposes. Returns the result of the executed expression.
@@ -204,7 +204,7 @@ def _incremental_compile_module(
204204
py_ast: GeneratedPyAST,
205205
module: BasilispModule,
206206
source_filename: str,
207-
collect_bytecode: Optional[BytecodeCollector] = None,
207+
collect_bytecode: BytecodeCollector | None = None,
208208
) -> None:
209209
"""Incrementally compile a stream of AST nodes in module mod.
210210
@@ -232,7 +232,7 @@ def _bootstrap_module(
232232
gctx: GeneratorContext,
233233
optimizer: PythonASTOptimizer,
234234
module: BasilispModule,
235-
collect_bytecode: Optional[BytecodeCollector] = None,
235+
collect_bytecode: BytecodeCollector | None = None,
236236
) -> None:
237237
"""Bootstrap a new module with imports and other boilerplate."""
238238
_incremental_compile_module(
@@ -249,7 +249,7 @@ def compile_module(
249249
forms: Iterable[ReaderForm],
250250
ctx: CompilerContext,
251251
module: BasilispModule,
252-
collect_bytecode: Optional[BytecodeCollector] = None,
252+
collect_bytecode: BytecodeCollector | None = None,
253253
) -> None:
254254
"""Compile an entire Basilisp module into Python bytecode which can be
255255
executed as a Python module.
@@ -298,7 +298,7 @@ def load(
298298
path: str,
299299
ctx: CompilerContext,
300300
ns: runtime.Namespace,
301-
collect_bytecode: Optional[BytecodeCollector] = None,
301+
collect_bytecode: BytecodeCollector | None = None,
302302
) -> Any:
303303
"""Call :lpy:fn:`basilisp.core/load` with the given ``path``, returning the
304304
result."""
@@ -311,7 +311,7 @@ def load_file(
311311
path: Path,
312312
ctx: CompilerContext,
313313
ns: runtime.Namespace,
314-
collect_bytecode: Optional[BytecodeCollector] = None,
314+
collect_bytecode: BytecodeCollector | None = None,
315315
) -> Any:
316316
"""Call :lpy:fn:`basilisp.core/load-file` with the given ``path``, returning the
317317
result."""

0 commit comments

Comments
 (0)