Skip to content

Commit

Permalink
src/conway_polynomials/__init__.py: add types for _open_database()
Browse files Browse the repository at this point in the history
Jump through some hoops to add type information to the new
_open_database() function. The return type of lzma.open()
had to be massaged, but mypy is happy now.
  • Loading branch information
orlitzky committed Jan 13, 2024
1 parent 40b3449 commit 70999ef
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions src/conway_polynomials/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@
"""

from typing import Optional, TextIO


def _parse_line(l: str) -> tuple[int, int, tuple[int,...]]:
r"""
Expand Down Expand Up @@ -89,7 +91,7 @@ def _parse_line(l: str) -> tuple[int, int, tuple[int,...]]:

return (p, n, coeffs)

def _open_database():
def _open_database() -> TextIO:
r"""
Open the database, possibly xz compressed.
Expand All @@ -98,16 +100,29 @@ def _open_database():
however, it would be annoying to have to build/install the package
to a temporary location before the test suite could be run. For
that reason we retain the uncompressed filename as a fallback.
Returns
-------
file : TextIO
A file-like object, opened for reading in text mode, representing the
database.
"""
from importlib.resources import files
import lzma
from importlib.resources import as_file, files
from io import TextIOWrapper

dbpath = files('conway_polynomials').joinpath('CPimport.txt')
try:
import lzma
return lzma.open(dbpath.with_suffix(".txt.xz"), "rt")
except FileNotFoundError:
return dbpath.open("r")
with as_file(dbpath) as p:
try:
# Open as binary and wrap in TextIO to guarantee
# that the return type is correct.
return TextIOWrapper(lzma.open(p.with_suffix(".txt.xz")))
except FileNotFoundError:
return open(p, "r")


from typing import Optional
_conway_dict: Optional[ dict[int,dict[int,tuple[int,...]]] ]
_conway_dict = None # cached result of database()
def database() -> dict[int,dict[int,tuple[int,...]]]:
Expand Down

0 comments on commit 70999ef

Please sign in to comment.