Skip to content

Commit 4893f1b

Browse files
committed
style: fix type annotations
1 parent 7e42e8a commit 4893f1b

4 files changed

Lines changed: 118 additions & 123 deletions

File tree

varname/core.py

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import ast
44
import re
55
import warnings
6-
from typing import Any, List, Union, Tuple, Type, Callable, overload
6+
from typing import Any, List, Union, Tuple, Type, Callable, Optional, overload
77

88
from executing import Source
99

@@ -27,11 +27,11 @@
2727

2828
def varname(
2929
frame: int = 1,
30-
ignore: IgnoreType = None,
30+
ignore: IgnoreType | None = None,
3131
multi_vars: bool = False,
3232
raise_exc: bool = True,
3333
strict: bool = True,
34-
) -> Union[str, Tuple[Union[str, Tuple], ...]]:
34+
) -> Optional[Union[str, Tuple[Union[str, Tuple], ...]]]:
3535
"""Get the name of the variable(s) that assigned by function call or
3636
class instantiation.
3737
@@ -148,10 +148,10 @@ class instantiation.
148148
)
149149
)
150150

151-
return names[0]
151+
return names[0] # type: ignore
152152

153153

154-
def will(frame: int = 1, raise_exc: bool = True) -> str:
154+
def will(frame: int = 1, raise_exc: bool = True) -> Optional[str]:
155155
"""Detect the attribute name right immediately after a function call.
156156
157157
Examples:
@@ -204,7 +204,7 @@ def will(frame: int = 1, raise_exc: bool = True) -> str:
204204
return None
205205

206206
# try to get node inst.attr from inst.attr()
207-
node = node.parent
207+
node = node.parent # type: ignore
208208

209209
# see test_will_fail
210210
if not isinstance(node, ast.Attribute):
@@ -309,12 +309,12 @@ def nameof(
309309
# We don't have to check keyword arguments here, as the instruction
310310
# will then be CALL_FUNCTION_KW.
311311
if not more_vars:
312-
return bytecode_nameof(frameobj.f_code, frameobj.f_lasti)
312+
return bytecode_nameof(frameobj.f_code, frameobj.f_lasti) # type: ignore
313313

314314
# We are anyway raising exceptions, no worries about additional burden
315315
# of frame retrieval again
316-
source = frameobj.f_code.co_filename
317-
if source == "<stdin>":
316+
source = frameobj.f_code.co_filename # type: ignore
317+
if source == "<stdin>": # pragma: no cover
318318
raise VarnameRetrievingError(
319319
"Are you trying to call nameof in REPL/python shell? "
320320
"In such a case, nameof can only be called with single "
@@ -345,10 +345,10 @@ def nameof(
345345
def argname(
346346
arg: str,
347347
*,
348-
func: Callable = None,
349-
dispatch: Type = None,
348+
func: Optional[Callable] = None,
349+
dispatch: Optional[Type] = None,
350350
frame: int = 1,
351-
ignore: IgnoreType = None,
351+
ignore: Optional[IgnoreType] = None,
352352
vars_only: bool = True,
353353
) -> ArgSourceType: # pragma: no cover
354354
...
@@ -360,10 +360,10 @@ def argname(
360360
more_arg: str,
361361
/, # introduced in python 3.8
362362
*more_args: str,
363-
func: Callable = None,
364-
dispatch: Type = None,
363+
func: Optional[Callable] = None,
364+
dispatch: Optional[Type] = None,
365365
frame: int = 1,
366-
ignore: IgnoreType = None,
366+
ignore: Optional[IgnoreType] = None,
367367
vars_only: bool = True,
368368
) -> Tuple[ArgSourceType, ...]: # pragma: no cover
369369
...
@@ -372,10 +372,10 @@ def argname(
372372
def argname(
373373
arg: str,
374374
*more_args: str,
375-
func: Callable = None,
376-
dispatch: Type = None,
375+
func: Optional[Callable] = None,
376+
dispatch: Optional[Type] = None,
377377
frame: int = 1,
378-
ignore: IgnoreType = None,
378+
ignore: Optional[IgnoreType] = None,
379379
vars_only: bool = True,
380380
) -> Union[ArgSourceType, Tuple[ArgSourceType, ...]]:
381381
"""Get the names/sources of arguments passed to a function.
@@ -456,10 +456,10 @@ def argname(
456456
func_node = reconstruct_func_node(func_node)
457457

458458
if not func:
459-
func = get_function_called_argname(func_frame, func_node)
459+
func = get_function_called_argname(func_frame, func_node) # type: ignore
460460

461461
if dispatch:
462-
func = func.dispatch(dispatch)
462+
func = func.dispatch(dispatch) # type: ignore
463463

464464
# don't pass the target arguments so that we can cache the sources in
465465
# the same call. For example:
@@ -468,9 +468,9 @@ def argname(
468468
# >>> b_name = argname(b)
469469
try:
470470
argument_sources = get_argument_sources(
471-
Source.for_frame(func_frame),
471+
Source.for_frame(func_frame), # type: ignore
472472
func_node,
473-
func,
473+
func, # type: ignore
474474
vars_only=vars_only,
475475
)
476476
except Exception as err:
@@ -483,13 +483,13 @@ def argname(
483483
for farg in (arg, *more_args):
484484

485485
farg_name = farg
486-
farg_subscript = None # type: str | int
486+
farg_subscript = None # type: Optional[str]
487487
match = re.match(r"^([\w_]+)\[(.+)\]$", farg)
488488
if match:
489489
farg_name = match.group(1)
490490
farg_subscript = match.group(2)
491-
if farg_subscript.isdigit():
492-
farg_subscript = int(farg_subscript)
491+
if farg_subscript.isdigit(): # type: ignore
492+
farg_subscript = int(farg_subscript) # type: ignore
493493
else:
494494
match = re.match(r"^\*([\w_]+)$", farg)
495495
if match:

varname/helpers.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,17 @@
44
import inspect
55
from functools import partial, wraps
66
from os import PathLike
7-
from typing import Any, Callable, Dict, Tuple, Type, Union
7+
from typing import Any, Callable, Dict, Tuple, Type, Union, Optional
88

99
from .utils import IgnoreType
1010
from .ignore import IgnoreList
1111
from .core import argname, varname
1212

1313

1414
def register(
15-
cls_or_func: type = None,
15+
cls_or_func: Optional[Type] = None,
1616
frame: int = 1,
17-
ignore: IgnoreType = None,
17+
ignore: Optional[IgnoreType] = None,
1818
multi_vars: bool = False,
1919
raise_exc: bool = True,
2020
strict: bool = True,
@@ -130,7 +130,7 @@ def __init__(
130130
self,
131131
value: Any,
132132
frame: int = 1,
133-
ignore: IgnoreType = None,
133+
ignore: Optional[IgnoreType] = None,
134134
raise_exc: bool = True,
135135
strict: bool = True,
136136
):
@@ -240,12 +240,12 @@ def debug(
240240

241241
def exec_code(
242242
code: str,
243-
globals: Dict[str, Any] = None,
244-
locals: Dict[str, Any] = None,
243+
globals: Optional[Dict[str, Any]] = None,
244+
locals: Optional[Dict[str, Any]] = None,
245245
/,
246-
sourcefile: PathLike | str = None,
246+
sourcefile: Optional[PathLike | str] = None,
247247
frame: int = 1,
248-
ignore: IgnoreType = None,
248+
ignore: Optional[IgnoreType] = None,
249249
**kwargs: Any,
250250
) -> None:
251251
"""Execute code where source code is visible at runtime.
@@ -297,9 +297,9 @@ def exec_code(
297297
ignore_list = IgnoreList.create(ignore)
298298
frame_info = ignore_list.get_frame(frame)
299299
if globals is None:
300-
globals = frame_info.f_globals
300+
globals = frame_info.f_globals # type: ignore
301301
if locals is None:
302-
locals = frame_info.f_locals
302+
locals = frame_info.f_locals # type: ignore
303303

304304
try:
305305
exec(compile(code, sourcefile, "exec"), globals, locals, **kwargs)

varname/ignore.py

Lines changed: 26 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,25 +17,27 @@
1717
<lambda> are ignored by default.
1818
1919
"""
20+
2021
import sys
2122
import inspect
2223
import warnings
2324
from os import path
2425
from pathlib import Path
2526
from fnmatch import fnmatch
2627
from abc import ABC, abstractmethod
27-
from typing import List, Union
28+
from typing import List, Union, Optional
2829
from types import FrameType, ModuleType, FunctionType
2930

3031
from executing import Source
3132

3233
try:
3334
import sysconfig # 3.10+
3435
except ImportError: # pragma: no cover
35-
from distutils import sysconfig
36+
from distutils import sysconfig # type: ignore
37+
3638
STANDLIB_PATH = sysconfig.get_python_lib(standard_lib=True)
3739
else:
38-
STANDLIB_PATH = sysconfig.get_path('stdlib')
40+
STANDLIB_PATH = sysconfig.get_path("stdlib")
3941

4042
from .utils import (
4143
IgnoreElemType,
@@ -52,6 +54,13 @@
5254
class IgnoreElem(ABC):
5355
"""An element of the ignore list"""
5456

57+
module: ModuleType
58+
filename: str
59+
dirname: str
60+
func: FunctionType
61+
n_decor: int
62+
qualname: str
63+
5564
def __init_subclass__(cls, attrs: List[str]) -> None:
5665
"""Define different attributes for subclasses"""
5766

@@ -120,9 +129,7 @@ def match(self, frame_no: int, frameinfos: List[inspect.FrameInfo]) -> bool:
120129
frame = frameinfos[frame_no].frame
121130

122131
# in case of symbolic links
123-
return path.realpath(frame.f_code.co_filename) == path.realpath(
124-
self.filename
125-
)
132+
return path.realpath(frame.f_code.co_filename) == path.realpath(self.filename)
126133

127134

128135
class IgnoreDirname(IgnoreElem, attrs=["dirname"]):
@@ -220,9 +227,7 @@ def match(self, frame_no: int, frameinfos: List[inspect.FrameInfo]) -> bool:
220227
if module and module != self.module:
221228
return False
222229

223-
if not module and not frame_matches_module_by_ignore_id(
224-
frame, self.module
225-
):
230+
if not module and not frame_matches_module_by_ignore_id(frame, self.module):
226231
return False
227232

228233
source = Source.for_frame(frame)
@@ -231,7 +236,10 @@ def match(self, frame_no: int, frameinfos: List[inspect.FrameInfo]) -> bool:
231236
return fnmatch(source.code_qualname(frame.f_code), self.qualname)
232237

233238

234-
class IgnoreFilenameQualname(IgnoreElem, attrs=["filename", "qualname"]):
239+
class IgnoreFilenameQualname(
240+
IgnoreElem,
241+
attrs=["filename", "qualname"],
242+
): # pragma: no cover
235243
"""Ignore calls with given qualname in the module with the filename"""
236244

237245
def match(self, frame_no: int, frameinfos: List[inspect.FrameInfo]) -> bool:
@@ -284,7 +292,7 @@ def create_ignore_elem(ignore_elem: IgnoreElemType) -> IgnoreElem:
284292

285293
if isinstance(ignore_elem[0], ModuleType):
286294
return IgnoreModuleQualname(*ignore_elem) # type: ignore
287-
if isinstance(ignore_elem[0], (Path, str)):
295+
if isinstance(ignore_elem[0], (Path, str)): # pragma: no cover
288296
return IgnoreFilenameQualname(*ignore_elem) # type: ignore
289297
if ignore_elem[0] is None:
290298
return IgnoreOnlyQualname(*ignore_elem)
@@ -298,7 +306,7 @@ class IgnoreList:
298306
@classmethod
299307
def create(
300308
cls,
301-
ignore: IgnoreType = None,
309+
ignore: Optional[IgnoreType] = None,
302310
ignore_lambda: bool = True,
303311
ignore_varname: bool = True,
304312
) -> "IgnoreList":
@@ -324,9 +332,9 @@ def create(
324332
IgnoreStdlib(STANDLIB_PATH) # type: ignore
325333
] # type: List[IgnoreElem]
326334
if ignore_varname:
327-
ignore_list.append(create_ignore_elem(sys.modules[__package__]))
335+
ignore_list.append(create_ignore_elem(sys.modules[__package__ or __name__]))
328336
if ignore_lambda:
329-
ignore_list.append(create_ignore_elem((None, "*<lambda>")))
337+
ignore_list.append(create_ignore_elem((None, "*<lambda>"))) # type: ignore
330338
for ignore_elem in ignore:
331339
ignore_list.append(create_ignore_elem(ignore_elem))
332340

@@ -355,19 +363,15 @@ def nextframe_to_check(
355363
for ignore_elem in self.ignore_list:
356364
matched = ignore_elem.match(frame_no, frameinfos) # type: ignore
357365
if matched and isinstance(ignore_elem, IgnoreDecorated):
358-
debug_ignore_frame(
359-
f"Ignored by {ignore_elem!r}", frameinfos[frame_no]
360-
)
366+
debug_ignore_frame(f"Ignored by {ignore_elem!r}", frameinfos[frame_no])
361367
return ignore_elem.n_decor + 1
362368

363369
if matched:
364-
debug_ignore_frame(
365-
f"Ignored by {ignore_elem!r}", frameinfos[frame_no]
366-
)
370+
debug_ignore_frame(f"Ignored by {ignore_elem!r}", frameinfos[frame_no])
367371
return 1
368372
return 0
369373

370-
def get_frame(self, frame_no: int) -> FrameType:
374+
def get_frame(self, frame_no: int) -> Optional[FrameType]:
371375
"""Get the right frame by the frame number
372376
373377
Args:
@@ -397,9 +401,7 @@ def get_frame(self, frame_no: int) -> FrameType:
397401
debug_ignore_frame("Gotcha!", frames[i])
398402
return frames[i].frame
399403

400-
debug_ignore_frame(
401-
f"Skipping ({frame_no - 1} more to skip)", frames[i]
402-
)
404+
debug_ignore_frame(f"Skipping ({frame_no - 1} more to skip)", frames[i])
403405
i += 1
404406

405407
except Exception as exc:

0 commit comments

Comments
 (0)