Skip to content

Commit 7b19daf

Browse files
committed
Switch to using modern Python union syntax
1 parent f643d88 commit 7b19daf

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

+518
-496
lines changed

src/basilisp/cli.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
import types
99
from collections.abc import Sequence
1010
from pathlib import Path
11-
from typing import Any, Callable, Optional, Union
11+
from typing import Any, Optional, Union
12+
from collections.abc import Callable
1213

1314
from basilisp import main as basilisp
1415
from basilisp.lang import compiler as compiler
@@ -97,7 +98,7 @@ def prepend_once(path: str) -> None:
9798
prepend_once(unsafe_path)
9899

99100

100-
def _to_bool(v: Optional[str]) -> Optional[bool]:
101+
def _to_bool(v: str | None) -> bool | None:
101102
"""Coerce a string argument to a boolean value, if possible."""
102103
if v is None:
103104
return v
@@ -389,8 +390,8 @@ def _add_runtime_arg_group(parser: argparse.ArgumentParser) -> None:
389390
def _subcommand(
390391
subcommand: str,
391392
*,
392-
help: Optional[str] = None, # pylint: disable=redefined-builtin
393-
description: Optional[str] = None,
393+
help: str | None = None, # pylint: disable=redefined-builtin
394+
description: str | None = None,
394395
handler: Handler,
395396
allows_extra: bool = False,
396397
) -> Callable[
@@ -810,7 +811,7 @@ def run_script():
810811
os.execvp("basilisp", args) # nosec B606, B607
811812

812813

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

src/basilisp/contrib/pytest/testrunner.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
from collections.abc import Iterable, Iterator
77
from pathlib import Path
88
from types import GeneratorType
9-
from typing import Callable, Optional
9+
from typing import Optional
10+
from collections.abc import Callable
1011

1112
import pytest
1213

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

110111
@staticmethod
111-
def _run_fixture(fixture: FixtureFunction) -> Optional[Iterator[None]]:
112+
def _run_fixture(fixture: FixtureFunction) -> Iterator[None] | None:
112113
"""Run a fixture function. If the fixture is a generator function, return the
113114
generator/coroutine. Otherwise, simply return the value from the function, if
114115
one."""
@@ -199,7 +200,7 @@ class BasilispFile(pytest.File):
199200

200201
def __init__(self, **kwargs) -> None:
201202
super().__init__(**kwargs)
202-
self._fixture_manager: Optional[FixtureManager] = None
203+
self._fixture_manager: FixtureManager | None = None
203204

204205
@staticmethod
205206
def _collected_fixtures(
@@ -248,7 +249,7 @@ def _import_module(self) -> runtime.BasilispModule:
248249
modnames = _get_fully_qualified_module_names(self.path)
249250
assert modnames, "Must have at least one module name"
250251

251-
exc: Optional[ModuleNotFoundError] = None
252+
exc: ModuleNotFoundError | None = None
252253
for modname in modnames:
253254
try:
254255
module = importlib.import_module(modname)
@@ -360,7 +361,7 @@ def runtest(self):
360361
If any tests fail, raise an ExceptionInfo exception with the test failures.
361362
PyTest will invoke self.repr_failure to display the failures to the user."""
362363
results: lmap.PersistentMap = self._run_test()
363-
failures: Optional[vec.PersistentVector] = results.val_at(_FAILURES_KW)
364+
failures: vec.PersistentVector | None = results.val_at(_FAILURES_KW)
364365
if runtime.to_seq(failures):
365366
raise TestFailuresInfo("Test failures", lmap.map(results))
366367

@@ -391,7 +392,7 @@ def repr_failure(self, excinfo, style=None):
391392
def reportinfo(self):
392393
return self.fspath, 0, self.name
393394

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

src/basilisp/contrib/sphinx/autodoc.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -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: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -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: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -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: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import threading
2-
from typing import Callable, Generic, Optional, TypeVar
2+
from typing import Generic, Optional, TypeVar
3+
from collections.abc import Callable
34

4-
from typing_extensions import Concatenate, ParamSpec
5+
from typing_extensions import ParamSpec
6+
from typing import Concatenate
57

68
from basilisp.lang import map as lmap
79
from basilisp.lang.interfaces import IPersistentMap, RefValidator
@@ -17,10 +19,10 @@ class Atom(RefBase[T], Generic[T]):
1719
def __init__(
1820
self,
1921
state: T,
20-
meta: Optional[IPersistentMap] = None,
21-
validator: Optional[RefValidator] = None,
22+
meta: IPersistentMap | None = None,
23+
validator: RefValidator | None = None,
2224
) -> None:
23-
self._meta: Optional[IPersistentMap] = meta
25+
self._meta: IPersistentMap | None = meta
2426
self._state = state
2527
self._lock = threading.RLock()
2628
self._watches = lmap.EMPTY

src/basilisp/lang/compiler/__init__.py

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
from ast import unparse
66
from collections.abc import Iterable
77
from pathlib import Path
8-
from typing import Any, Callable, Optional
8+
from typing import Any, Optional
9+
from collections.abc import Callable
910

1011
from basilisp.lang import list as llist
1112
from basilisp.lang import map as lmap
@@ -60,7 +61,7 @@ def to_py_str(t: ast.AST) -> str:
6061
class CompilerContext:
6162
__slots__ = ("_filename", "_actx", "_gctx", "_optimizer")
6263

63-
def __init__(self, filename: str, opts: Optional[CompilerOpts] = None):
64+
def __init__(self, filename: str, opts: CompilerOpts | None = None):
6465
self._filename = filename
6566
self._actx = AnalyzerContext(filename=filename, opts=opts)
6667
self._gctx = GeneratorContext(filename=filename, opts=opts)
@@ -84,15 +85,15 @@ def py_ast_optimizer(self) -> PythonASTOptimizer:
8485

8586

8687
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,
88+
generate_auto_inlines: bool | None = None,
89+
inline_functions: bool | None = None,
90+
warn_on_arity_mismatch: bool | None = None,
91+
warn_on_shadowed_name: bool | None = None,
92+
warn_on_shadowed_var: bool | None = None,
93+
warn_on_unused_names: bool | None = None,
94+
warn_on_non_dynamic_set: bool | None = None,
95+
use_var_indirection: bool | None = None,
96+
warn_on_var_indirection: bool | None = None,
9697
) -> CompilerOpts:
9798
"""Return a map of compiler options with defaults applied."""
9899
return lmap.map(
@@ -148,7 +149,7 @@ def compile_and_exec_form(
148149
ctx: CompilerContext,
149150
ns: runtime.Namespace,
150151
wrapped_fn_name: str = _DEFAULT_FN,
151-
collect_bytecode: Optional[BytecodeCollector] = None,
152+
collect_bytecode: BytecodeCollector | None = None,
152153
) -> Any:
153154
"""Compile and execute the given form. This function will be most useful
154155
for the REPL and testing purposes. Returns the result of the executed expression.
@@ -204,7 +205,7 @@ def _incremental_compile_module(
204205
py_ast: GeneratedPyAST,
205206
module: BasilispModule,
206207
source_filename: str,
207-
collect_bytecode: Optional[BytecodeCollector] = None,
208+
collect_bytecode: BytecodeCollector | None = None,
208209
) -> None:
209210
"""Incrementally compile a stream of AST nodes in module mod.
210211
@@ -232,7 +233,7 @@ def _bootstrap_module(
232233
gctx: GeneratorContext,
233234
optimizer: PythonASTOptimizer,
234235
module: BasilispModule,
235-
collect_bytecode: Optional[BytecodeCollector] = None,
236+
collect_bytecode: BytecodeCollector | None = None,
236237
) -> None:
237238
"""Bootstrap a new module with imports and other boilerplate."""
238239
_incremental_compile_module(
@@ -249,7 +250,7 @@ def compile_module(
249250
forms: Iterable[ReaderForm],
250251
ctx: CompilerContext,
251252
module: BasilispModule,
252-
collect_bytecode: Optional[BytecodeCollector] = None,
253+
collect_bytecode: BytecodeCollector | None = None,
253254
) -> None:
254255
"""Compile an entire Basilisp module into Python bytecode which can be
255256
executed as a Python module.
@@ -298,7 +299,7 @@ def load(
298299
path: str,
299300
ctx: CompilerContext,
300301
ns: runtime.Namespace,
301-
collect_bytecode: Optional[BytecodeCollector] = None,
302+
collect_bytecode: BytecodeCollector | None = None,
302303
) -> Any:
303304
"""Call :lpy:fn:`basilisp.core/load` with the given ``path``, returning the
304305
result."""
@@ -311,7 +312,7 @@ def load_file(
311312
path: Path,
312313
ctx: CompilerContext,
313314
ns: runtime.Namespace,
314-
collect_bytecode: Optional[BytecodeCollector] = None,
315+
collect_bytecode: BytecodeCollector | None = None,
315316
) -> Any:
316317
"""Call :lpy:fn:`basilisp.core/load-file` with the given ``path``, returning the
317318
result."""

0 commit comments

Comments
 (0)