Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade flake8 use typedecl 2 #340

Merged
merged 5 commits into from
Feb 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
# Testing / QA
-r requirements-tests.txt
mypy >=0.931
flake8==5.0.4
flake8
flake8-docstrings
autopep8
types-requests
4 changes: 2 additions & 2 deletions src/psij/_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ def _register_plugin(desc: Descriptor, root_path: str, type: str,
if desc.name not in store:
store[desc.name] = []
existing = store[desc.name]
entry = _VersionEntry(desc.version, desc_path=desc.path, plugin_path=mod_path,
ecls=cls, exc=exc) # type: _VersionEntry[T]
entry: _VersionEntry[T] = _VersionEntry(desc.version, desc_path=desc.path,
plugin_path=mod_path, ecls=cls, exc=exc)
# check if an object with this version already exists
index = bisect_left(existing, entry)
if index != len(existing) and existing[index].version == desc.version:
Expand Down
6 changes: 3 additions & 3 deletions src/psij/executors/batch/batch_scheduler_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ def _attrs_to_mustache(job: Job) -> Dict[str, Union[object, List[Dict[str, objec
if not job.spec.attributes or not job.spec.attributes._custom_attributes:
return {}

r = {} # type: Dict[str, Union[object, List[Dict[str, object]]]]
r: Dict[str, Union[object, List[Dict[str, object]]]] = {}

for k, v in job.spec.attributes._custom_attributes.items():
ks = k.split('.', maxsplit=1)
if len(ks) == 2:
if ks[0] not in r:
r[ks[0]] = [] # type[List[Dict[str, object]]
r[ks[0]] = []
cast(List[Dict[str, object]], r[ks[0]]).append({'key': ks[1], 'value': v})
else:
r[k] = v
Expand Down Expand Up @@ -563,7 +563,7 @@ def __init__(self, name: str, config: BatchSchedulerExecutorConfig,
self.config = config
self.executor = executor
# native_id -> job
self._jobs = {} # type: Dict[str, List[Job]]
self._jobs: Dict[str, List[Job]] = {}
# counts consecutive errors while invoking qstat or equivalent
self._poll_error_count = 0
self._jobs_lock = RLock()
Expand Down
16 changes: 8 additions & 8 deletions src/psij/executors/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ class _ProcessEntry(ABC):
def __init__(self, job: Job, executor: 'LocalJobExecutor', launcher: Optional[Launcher]):
self.job = job
self.executor = executor
self.exit_code = None # type: Optional[int]
self.done_time = None # type: Optional[float]
self.out = None # type: Optional[str]
self.exit_code: Optional[int] = None
self.done_time: Optional[float] = None
self.out: Optional[str] = None
self.kill_flag = False
self.process = None # type: Optional[subprocess.Popen[bytes]]
self.process: Optional[subprocess.Popen[bytes]] = None
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's an interesting one - haven't seen that documented as type. Where did you find this?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://docs.python.org/3/library/subprocess.html#subprocess.Popen

It turns out Popen is a class. You'd think it's something like Open returning a File or, you know, Verb applied to Noun produces Noun, but no.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, sorry, I wasn't clear. Yes, Popen is a class - but classname[bytes] is not a syntax I have seen anywhere before.

I found one google hit by now which indicates that the Popen class is marked as generic - wasn't aware of that...

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see. Well, if you don't put the type parameters, mypy will produce an error. I'm not entirely sure where I found what that parameter is (str/bytes based on whether you open the output streams in text or binary mode), since I can't find a clear statement of that in the official python documentation.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thx, good to know.

self.launcher = launcher

@abstractmethod
Expand Down Expand Up @@ -80,7 +80,7 @@ def kill(self) -> None:
def poll(self) -> Tuple[Optional[int], Optional[str]]:
try:
assert self.process
ec = self.process.wait(timeout=0) # type: Optional[int]
ec: Optional[int] = self.process.wait(timeout=0)
if ec is None:
return 0, None
else:
Expand All @@ -105,7 +105,7 @@ def _get_env(spec: JobSpec) -> Optional[Dict[str, str]]:


class _ProcessReaper(threading.Thread):
_instance = None # type: _ProcessReaper
_instance: Optional['_ProcessReaper'] = None
_lock = threading.RLock()

@classmethod
Expand All @@ -118,7 +118,7 @@ def get_instance(cls: Type['_ProcessReaper']) -> '_ProcessReaper':

def __init__(self) -> None:
super().__init__(name='Local Executor Process Reaper', daemon=True)
self._jobs = {} # type: Dict[Job, _ProcessEntry]
self._jobs: Dict[Job, _ProcessEntry] = {}
self._lock = threading.RLock()

def register(self, entry: _ProcessEntry) -> None:
Expand All @@ -137,7 +137,7 @@ def run(self) -> None:
time.sleep(_REAPER_SLEEP_TIME)

def _check_processes(self) -> None:
done = [] # type: List[_ProcessEntry]
done: List[_ProcessEntry] = []
for entry in self._jobs.values():
if entry.kill_flag:
entry.kill()
Expand Down
6 changes: 3 additions & 3 deletions src/psij/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@ def __init__(self, spec: Optional[JobSpec] = None) -> None:
self._id = _generate_id()
self._status = JobStatus(JobState.NEW)
# need indirect ref to avoid a circular reference
self.executor = None # type: Optional['psij.JobExecutor']
self.executor: Optional['psij.JobExecutor'] = None
# allow the native ID to be anything and do the string conversion in the getter; there's
# no point in storing integers as strings.
self._native_id = None # type: Optional[object]
self._cb = None # type: Optional[JobStatusCallback]
self._native_id: Optional[object] = None
self._cb: Optional[JobStatusCallback] = None
self._status_cv = threading.Condition()
if logger.isEnabledFor(logging.DEBUG):
logger.debug('New Job: {}'.format(self))
Expand Down
6 changes: 3 additions & 3 deletions src/psij/job_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
class JobExecutor(ABC):
"""An abstract base class for all JobExecutor implementations."""

_executors = {} # type: Dict[str, List[_VersionEntry['JobExecutor']]]
_executors: Dict[str, List[_VersionEntry['JobExecutor']]] = {}

def __init__(self, url: Optional[str] = None,
config: Optional[JobExecutorConfig] = None):
Expand All @@ -40,9 +40,9 @@ def __init__(self, url: Optional[str] = None,
assert config
self.config = config
# _cb is not thread-safe; changing it while jobs are running could lead to badness
self._cb = None # type: Optional[JobStatusCallback]
self._cb: Optional[JobStatusCallback] = None
self._launchers_lock = RLock()
self._launchers = {} # type: Dict[str, Launcher]
self._launchers: Dict[str, Launcher] = {}

@property
def name(self) -> str:
Expand Down
2 changes: 1 addition & 1 deletion src/psij/job_launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
class Launcher(ABC):
"""An abstract base class for all launchers."""

_launchers = {} # type: Dict[str, List[_VersionEntry['Launcher']]]
_launchers: Dict[str, List[_VersionEntry['Launcher']]] = {}
DEFAULT_LAUNCHER_NAME = 'single'

def __init__(self, config: Optional[JobExecutorConfig] = None) -> None:
Expand Down
8 changes: 4 additions & 4 deletions src/psij/job_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class JobState(bytes, Enum):

def __new__(cls, index: int, order: int, name: str, final: bool) -> 'JobState': # noqa: D102
# This is used internally to allow enum initialization with multiple parameters
obj = bytes.__new__(cls) # type: 'JobState'
obj: 'JobState' = bytes.__new__(cls)
obj._value_ = index
obj._order = order
obj._name = name
Expand All @@ -20,9 +20,9 @@ def __new__(cls, index: int, order: int, name: str, final: bool) -> 'JobState':

def __init__(self, *args: object) -> None: # noqa: D107
# this is only here to declare the types of the properties
self._order = self._order # type: int
self._name = self._name # type: str
self._final = self._final # type: bool
self._order: int = self._order
self._name: str = self._name
self._final: bool = self._final

NEW = (0, 0, 'NEW', False)
"""
Expand Down
2 changes: 1 addition & 1 deletion src/psij/launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
class Launcher(ABC):
"""An abstract base class for all launchers."""

_launchers = {} # type: Dict[str, List[_VersionEntry['Launcher']]]
_launchers: Dict[str, List[_VersionEntry['Launcher']]] = {}
DEFAULT_LAUNCHER_NAME = 'single'

def __init__(self, config: Optional[JobExecutorConfig] = None) -> None:
Expand Down
4 changes: 2 additions & 2 deletions tests/executor_test_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ def __init__(self, spec: str, custom_attributes: Optional[Dict[str, object]] = N
spec_l = re.split(':', spec, maxsplit=2)
self.executor = spec_l[0]
if len(spec_l) > 1:
self.launcher = spec_l[1] # type: Optional[str]
self.launcher: Optional[str] = spec_l[1]
else:
self.launcher = None
if len(spec_l) == 3:
self.url = spec_l[2] # type: Optional[str]
self.url: Optional[str] = spec_l[2]
else:
self.url = None

Expand Down