Skip to content

Commit

Permalink
add type hints (#109)
Browse files Browse the repository at this point in the history
* add type hints

* finish with types and add py.typed file

* replace pipe by union and list by typing.List

* missing Union

* use Set instead of set for typing

* fix typing and format issue

* fix typing for python 3.8 for tuple and list
  • Loading branch information
Gryfenfer97 authored Oct 1, 2023
1 parent 9a0dec1 commit 91614ce
Show file tree
Hide file tree
Showing 7 changed files with 93 additions and 63 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,4 @@ coverage.xml
*,cover

.tox
venv
5 changes: 3 additions & 2 deletions scooby/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@
import argparse
import importlib
import sys
from typing import Any, Dict, List, Optional

import scooby
from scooby.report import Report


def main(args=None):
def main(args: Optional[List[str]] = None):
"""Parse command line inputs of CLI interface."""
# If not explicitly called, catch arguments
if args is None:
Expand Down Expand Up @@ -51,7 +52,7 @@ def main(args=None):
act(vars(parser.parse_args(args)))


def act(args_dict):
def act(args_dict: Dict[str, Any]) -> None:
"""Act upon CLI inputs."""
# Quick exit if only scooby version.
if args_dict.pop('version'):
Expand Down
28 changes: 13 additions & 15 deletions scooby/knowledge.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import os
import sys
import sysconfig
from typing import Callable, Dict, List, Literal, Set, Tuple, Union

# Define unusual version locations
VERSION_ATTRIBUTES = {
Expand All @@ -21,7 +22,7 @@
}


def get_pyqt5_version():
def get_pyqt5_version() -> str:
"""Return the PyQt5 version."""
try:
from PyQt5.Qt import PYQT_VERSION_STR
Expand All @@ -31,13 +32,13 @@ def get_pyqt5_version():
return PYQT_VERSION_STR


VERSION_METHODS = {
VERSION_METHODS: Dict[str, Callable[[], str]] = {
'PyQt5': get_pyqt5_version,
}


# Check the environments
def in_ipython():
def in_ipython() -> bool:
"""Check if we are in a IPython environment.
Returns
Expand All @@ -52,7 +53,7 @@ def in_ipython():
return False


def in_ipykernel():
def in_ipykernel() -> bool:
"""Check if in a ipykernel (most likely Jupyter) environment.
Warning
Expand All @@ -70,13 +71,13 @@ def in_ipykernel():
ipykernel = False
if in_ipython():
try:
ipykernel = type(get_ipython()).__module__.startswith('ipykernel.')
ipykernel: bool = type(get_ipython()).__module__.startswith('ipykernel.')
except NameError:
pass
return ipykernel


def get_standard_lib_modules():
def get_standard_lib_modules() -> Set[str]:
"""Return a set of the names of all modules in the standard library."""
site_path = sysconfig.get_path('stdlib')
if getattr(sys, 'frozen', False): # within pyinstaller
Expand All @@ -86,11 +87,7 @@ def get_standard_lib_modules():
else:
names = []

stdlib_pkgs = []
for name in names:
if name.endswith(".py"):
stdlib_pkgs.append(name[:-3])
stdlib_pkgs = set(stdlib_pkgs)
stdlib_pkgs = {name[:-3] for name in names if name.endswith(".py")}

else:
names = os.listdir(site_path)
Expand Down Expand Up @@ -119,7 +116,7 @@ def get_standard_lib_modules():
return stdlib_pkgs


def version_tuple(v):
def version_tuple(v: str) -> Tuple[int, ...]:
"""Convert a version string to a tuple containing ints.
Non-numeric version strings will be converted to 0. For example:
Expand All @@ -138,7 +135,7 @@ def version_tuple(v):
if len(split_v) > 3:
raise ValueError('Version strings containing more than three parts ' 'cannot be parsed')

vals = []
vals: List[int] = []
for item in split_v:
if item.isnumeric():
vals.append(int(item))
Expand All @@ -148,7 +145,7 @@ def version_tuple(v):
return tuple(vals)


def meets_version(version, meets):
def meets_version(version: str, meets: str) -> bool:
"""Check if a version string meets a minimum version.
This is a simplified way to compare version strings. For a more robust
Expand Down Expand Up @@ -193,7 +190,7 @@ def meets_version(version, meets):
return True


def get_filesystem_type():
def get_filesystem_type() -> Union[str, Literal[False]]:
"""Get the type of the file system at the path of the scooby package."""
try:
import psutil # lazy-load see PR#85
Expand All @@ -203,6 +200,7 @@ def get_filesystem_type():
import platform # lazy-load see PR#85

# Skip Windows due to https://github.com/banesullivan/scooby/issues/75
fs_type: Union[str, Literal[False]]
if psutil and platform.system() != 'Windows':
# Code by https://stackoverflow.com/a/35291824/10504481
my_path = str(Path(__file__).resolve())
Expand Down
Empty file added scooby/py.typed
Empty file.
Loading

0 comments on commit 91614ce

Please sign in to comment.