From c92f60d1d067e3402a73b3d2add65cb841db1ffd Mon Sep 17 00:00:00 2001 From: "Mr. Python" <2789762371@qq.com> Date: Mon, 7 Oct 2024 22:44:11 +0800 Subject: [PATCH] Fix some type issue --- cyaron/io.py | 45 +++++++++++++++++++++++++-------------------- cyaron/sequence.py | 4 ++-- cyaron/vector.py | 38 +++++++++++++++++++++++++------------- 3 files changed, 52 insertions(+), 35 deletions(-) diff --git a/cyaron/io.py b/cyaron/io.py index f073b50..1ddb9ee 100644 --- a/cyaron/io.py +++ b/cyaron/io.py @@ -8,7 +8,7 @@ import re import subprocess import tempfile -from typing import Union, overload +from typing import Union, overload, Optional from io import IOBase from . import log from .utils import list_like, make_unicode @@ -19,29 +19,30 @@ class IO: @overload def __init__(self, - input_file: Union[IOBase, str, int, None] = None, - output_file: Union[IOBase, str, int, None] = None, - data_id: Union[str, None] = None, + input_file: Optional[Union[IOBase, str, int]] = None, + output_file: Optional[Union[IOBase, str, int]] = None, + data_id: Optional[int] = None, disable_output: bool = False): ... @overload def __init__(self, - data_id: Union[str, None] = None, - file_prefix: Union[str, None] = None, - input_suffix: Union[str, None] = '.in', - output_suffix: Union[str, None] = '.out', + data_id: Optional[int] = None, + file_prefix: Optional[str] = None, + input_suffix: str = '.in', + output_suffix: str = '.out', disable_output: bool = False): ... - def __init__(self, - input_file: Union[IOBase, str, int, None] = None, - output_file: Union[IOBase, str, int, None] = None, - data_id: Union[str, None] = None, - file_prefix: Union[str, None] = None, - input_suffix: Union[str, None] = '.in', - output_suffix: Union[str, None] = '.out', - disable_output: bool = False): + def __init__( # type: ignore + self, + input_file: Optional[Union[IOBase, str, int]] = None, + output_file: Optional[Union[IOBase, str, int]] = None, + data_id: Optional[int] = None, + file_prefix: Optional[str] = None, + input_suffix: str = '.in', + output_suffix: str = '.out', + disable_output: bool = False): """ Args: input_file (optional): input file object or filename or file descriptor. @@ -216,6 +217,8 @@ def output_gen(self, shell_cmd, time_limit=None): time_limit: the time limit (seconds) of the command to run. None means infinity. Defaults to None. """ + if self.output_file is None: + raise ValueError("Output file is disabled") self.flush_buffer() origin_pos = self.input_file.tell() self.input_file.seek(0) @@ -224,16 +227,16 @@ def output_gen(self, shell_cmd, time_limit=None): shell_cmd, shell=True, timeout=time_limit, - stdin=self.input_file, - stdout=self.output_file, + stdin=self.input_file.fileno(), + stdout=self.output_file.fileno(), universal_newlines=True, ) else: subprocess.check_call( shell_cmd, shell=True, - stdin=self.input_file, - stdout=self.output_file, + stdin=self.input_file.fileno(), + stdout=self.output_file.fileno(), universal_newlines=True, ) self.input_file.seek(origin_pos) @@ -248,6 +251,8 @@ def output_write(self, *args, **kwargs): *args: the elements to write separator: a string used to separate every element. Defaults to " ". """ + if self.output_file is None: + raise ValueError("Output file is disabled") self.__write(self.output_file, *args, **kwargs) def output_writeln(self, *args, **kwargs): diff --git a/cyaron/sequence.py b/cyaron/sequence.py index f1df388..4cf6ba3 100644 --- a/cyaron/sequence.py +++ b/cyaron/sequence.py @@ -19,8 +19,8 @@ class Sequence: def __init__(self, formula: Callable[[int, Callable[[int], T]], T], - initial_values: Optional[Union[List[T], Tuple[T, ...], - Dict[int, T]]] = ()): + initial_values: Union[List[T], Tuple[T, ...], Dict[int, + T]] = ()): """ Initialize a sequence object. Parameters: diff --git a/cyaron/vector.py b/cyaron/vector.py index 7ed60d8..5814fc9 100644 --- a/cyaron/vector.py +++ b/cyaron/vector.py @@ -4,7 +4,8 @@ import random from enum import IntEnum -from typing import Union, Tuple, List, Set +from typing import Sequence, Union, Tuple, List, Set +from typing import cast as typecast from .utils import list_like @@ -48,20 +49,21 @@ def random( dimension = len(position_range) - offset: List[_Number] = [] - length: List[_Number] = [] + offset: Sequence[_Number] = [] + length: Sequence[_Number] = [] vector_space = 1 for i in range(0, dimension): - if list_like(position_range[i]): - if position_range[i][1] < position_range[i][0]: + now_position_range = position_range[i] + if isinstance(now_position_range, tuple): + if now_position_range[1] < now_position_range[0]: raise ValueError( "upper-bound should be larger than lower-bound") - offset.append(position_range[i][0]) - length.append(position_range[i][1] - position_range[i][0]) + offset.append(now_position_range[0]) + length.append(now_position_range[1] - now_position_range[0]) else: offset.append(0) - length.append(position_range[i]) + length.append(now_position_range) vector_space *= (length[i] + 1) if mode == VectorRandomMode.unique and num > vector_space: @@ -69,7 +71,10 @@ def random( "1st param is so large that CYaRon can not generate unique vectors" ) + result: Union[List[List[int]], List[List[float]]] if mode == VectorRandomMode.repeatable: + offset = typecast(Sequence[int], offset) + length = typecast(Sequence[int], length) result = [[ random.randint(x, x + y) for x, y in zip(offset, length) ] for _ in range(num)] @@ -79,8 +84,11 @@ def random( ] for _ in range(num)] elif mode == VectorRandomMode.unique and vector_space > 5 * num: # O(NlogN) + offset = typecast(Sequence[int], offset) + length = typecast(Sequence[int], length) + vector_space = typecast(int, vector_space) num_set: Set[int] = set() - result: List[List[int]] = [] + result = typecast(List[List[int]], []) for i in range(0, num): while True: rand = random.randint(0, vector_space - 1) @@ -93,6 +101,9 @@ def random( result.append(tmp) else: # generate 0~vector_space and shuffle + offset = typecast(Sequence[int], offset) + length = typecast(Sequence[int], length) + vector_space = typecast(int, vector_space) rand_arr = list(range(0, vector_space)) random.shuffle(rand_arr) result = [ @@ -106,13 +117,14 @@ def random( return result @staticmethod - def get_vector(dimension: int, position_range: list, hashcode: int): + def get_vector(dimension: int, position_range: Sequence[int], + hashcode: int): """ Generates a vector based on the given dimension, position range, and hashcode. Args: - dimension (int): The number of dimensions for the vector. - position_range (list): A list of integers specifying the range for each dimension. - hashcode (int): A hashcode used to generate the vector. + dimension: The number of dimensions for the vector. + position_range: A list of integers specifying the range for each dimension. + hashcode: A hashcode used to generate the vector. Returns: list: A list representing the generated vector. """