Skip to content

Commit b2d7ae3

Browse files
author
Release Manager
committed
gh-41169: Type annotations and stubs for cachefunc Added missing stubs to `src/sage/misc/cachefunc.pyi` and annotations to `src/sage/misc/cachefunc.pyx`. This should fix some of the warnings when running `pyright` or `mypy` about not being able to import `cached_method` or `cached_function`. Also changed the default value of `do_pickle` from `None` to `False`. The behaviour of `None` was the same as the behaviour of `False`, so this simplifies the code (and the the added type annotations) with no change to behaviour. ### 📝 Checklist <!-- Put an `x` in all the boxes that apply. --> - [x] The title is concise and informative. - [x] The description explains in detail what this PR is about. - [ ] I have linked a relevant issue or discussion. - [ ] I have created tests covering the changes. - [ ] I have updated the documentation and checked the documentation preview. URL: #41169 Reported by: Vincent Macri Reviewer(s): Chenxin Zhong, Vincent Macri
2 parents e8c3270 + 5277938 commit b2d7ae3

File tree

3 files changed

+43
-39
lines changed

3 files changed

+43
-39
lines changed

src/sage/misc/cachefunc.pyi

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,16 @@ def dict_key(o: Any) -> Any:
77
def cache_key(o: Any) -> Any:
88
...
99

10+
def cached_method(f, name: str | None = None, key=None, do_pickle: bool = False) -> CachedMethod:
11+
...
12+
13+
def cached_function(f, name: str | None = None, key=None, do_pickle: bool = False) -> CachedFunction:
14+
...
15+
1016
class CachedFunction:
1117
def __init__(self, f: Callable, classmethod: bool = False,
1218
name: str | None = None, key: Callable | None = None,
13-
do_pickle: bool | None = None) -> None:
19+
do_pickle: bool = False) -> None:
1420
...
1521

1622
def __call__(self, *args: Any, **kwds: Any) -> Any:
@@ -40,7 +46,7 @@ class CachedFunction:
4046
class CachedMethod:
4147
def __init__(self, f: Callable, name: str | None = None,
4248
key: Callable | None = None,
43-
do_pickle: bool | None = None) -> None:
49+
do_pickle: bool = False) -> None:
4450
...
4551

4652
def __call__(self, inst: Any, *args: Any, **kwds: Any) -> Any:
@@ -58,7 +64,7 @@ class CacheDict(dict):
5864
class CachedInParentMethod(CachedMethod):
5965
def __init__(self, f: Callable, name: str | None = None,
6066
key: Callable | None = None,
61-
do_pickle: bool | None = None) -> None:
67+
do_pickle: bool = False) -> None:
6268
...
6369

6470
def _get_instance_cache(self, inst: Any) -> dict:
@@ -71,7 +77,7 @@ class CachedMethodCaller(CachedFunction):
7177
def __init__(self, cachedmethod: CachedMethod, inst: Any,
7278
cache: dict | None = None, name: str | None = None,
7379
key: Callable | None = None,
74-
do_pickle: bool | None = None) -> None:
80+
do_pickle: bool = False) -> None:
7581
...
7682

7783
def _instance_call(self, *args: Any, **kwds: Any) -> Any:
@@ -92,7 +98,7 @@ class CachedMethodCaller(CachedFunction):
9298
class CachedMethodCallerNoArgs(CachedFunction):
9399
def __init__(self, inst: Any, f: Callable, cache: Any = None,
94100
name: str | None = None,
95-
do_pickle: bool | None = None) -> None:
101+
do_pickle: bool = False) -> None:
96102
...
97103

98104
def _instance_call(self) -> Any:

src/sage/misc/cachefunc.pyx

Lines changed: 29 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -449,9 +449,11 @@ cdef extern from "methodobject.h":
449449
cdef int METH_NOARGS, METH_O
450450
cdef int PyCFunction_GetFlags(object op) except -1
451451

452+
from collections.abc import Iterator
453+
from inspect import isfunction
452454
import os
455+
453456
from sage.misc.sageinspect import sage_getfile_relative, sage_getsourcelines, sage_getargspec
454-
from inspect import isfunction
455457

456458
from sage.misc.weak_dict cimport CachedWeakValueDictionary
457459
from sage.misc.decorators import decorator_keywords
@@ -696,7 +698,7 @@ cdef class CachedFunction():
696698
sage: mul(1,1,algorithm='default') is mul(1,1,algorithm='algorithm') is mul(1,1) is mul(1,1,'default')
697699
True
698700
"""
699-
def __init__(self, f, *, classmethod=False, name=None, key=None, do_pickle=None):
701+
def __init__(self, f, *, classmethod=False, name: str | None = None, key=None, do_pickle: bool = False) -> None:
700702
"""
701703
Create a cached version of a function, which only recomputes
702704
values it hasn't already computed. A custom name can be
@@ -769,7 +771,7 @@ cdef class CachedFunction():
769771
self._common_init(f, None, name=name, key=key, do_pickle=do_pickle)
770772
self.cache = {} if do_pickle else NonpicklingDict()
771773
772-
def _common_init(self, f, argument_fixer, name=None, key=None, do_pickle=None):
774+
def _common_init(self, f, argument_fixer, name: str | None = None, key=None, do_pickle: bool = False) -> None:
773775
"""
774776
Perform initialization common to CachedFunction and CachedMethodCaller.
775777

@@ -798,7 +800,7 @@ cdef class CachedFunction():
798800
self._argument_fixer = argument_fixer
799801
800802
@property
801-
def __module__(self):
803+
def __module__(self) -> str:
802804
return self.__cached_module__
803805
804806
cdef get_key_args_kwds(self, tuple args, dict kwds):
@@ -1451,7 +1453,7 @@ cdef class WeakCachedFunction(CachedFunction):
14511453
sage: f.is_in_cache(t)
14521454
True
14531455
"""
1454-
def __init__(self, f, *, classmethod=False, name=None, key=None, **kwds):
1456+
def __init__(self, f, *, classmethod=False, name: str | None = None, key=None, **kwds) -> None:
14551457
"""
14561458
The inputs to the function must be hashable or they must define
14571459
:meth:`sage.structure.sage_object.SageObject._cache_key`.
@@ -1580,7 +1582,7 @@ class CachedMethodPickle():
15801582

15811583
- Simon King (2011-01)
15821584
"""
1583-
def __init__(self, inst, name, cache=None):
1585+
def __init__(self, inst, name, cache=None) -> None:
15841586
"""
15851587
INPUT:
15861588

@@ -1767,7 +1769,7 @@ cdef class CachedMethodCaller(CachedFunction):
17671769
sage: len(b.bar.cache)
17681770
1
17691771
"""
1770-
def __init__(self, CachedMethod cachedmethod, inst, *, cache=None, name=None, key=None, do_pickle=None):
1772+
def __init__(self, CachedMethod cachedmethod, inst, *, cache=None, name: str | None = None, key=None, do_pickle: bool = False) -> None:
17711773
"""
17721774
EXAMPLES::
17731775

@@ -2244,7 +2246,7 @@ cdef class CachedMethodCallerNoArgs(CachedFunction):
22442246

22452247
- Simon King (2011-04)
22462248
"""
2247-
def __init__(self, inst, f, cache=None, name=None, do_pickle=None):
2249+
def __init__(self, inst, f, cache=None, name: str | None = None, do_pickle: bool = False):
22482250
"""
22492251
EXAMPLES::
22502252

@@ -2657,7 +2659,7 @@ cdef class CachedMethod():
26572659
sage: b.f()
26582660
1
26592661
"""
2660-
def __init__(self, f, name=None, key=None, do_pickle=None):
2662+
def __init__(self, f, name: str | None = None, key=None, do_pickle: bool = False) -> None:
26612663
"""
26622664
EXAMPLES::
26632665

@@ -2728,7 +2730,7 @@ cdef class CachedMethod():
27282730
self.__cached_module__ = self._cachedfunc.__module__
27292731
27302732
@property
2731-
def __module__(self):
2733+
def __module__(self) -> str:
27322734
return self.__cached_module__
27332735
27342736
def __call__(self, inst, *args, **kwds):
@@ -3065,9 +3067,8 @@ cdef class CachedSpecialMethod(CachedMethod):
30653067
D[name] = Caller
30663068
return Caller
30673069
3068-
30693070
@decorator_keywords
3070-
def cached_method(f, name=None, key=None, do_pickle=None):
3071+
def cached_method(f, name: str | None = None, key=None, do_pickle: bool = False) -> CachedMethod:
30713072
"""
30723073
A decorator for cached methods.
30733074

@@ -3193,7 +3194,7 @@ cdef class CachedInParentMethod(CachedMethod):
31933194
Examples can be found at :mod:`~sage.misc.cachefunc`.
31943195
"""
31953196
3196-
def __init__(self, f, name=None, key=None, do_pickle=None):
3197+
def __init__(self, f, name: str | None = None, key=None, do_pickle: bool = False) -> None:
31973198
"""
31983199
Construct a new method with cache stored in the parent of the instance.
31993200

@@ -3359,7 +3360,7 @@ cdef class CachedInParentMethod(CachedMethod):
33593360
P._cached_methods = {}
33603361
return (<dict>P._cached_methods).setdefault(self._cache_name, default)
33613362
3362-
def __get__(self, inst, cls):
3363+
def __get__(self, inst, cls) -> GloballyCachedMethodCaller:
33633364
"""
33643365
Get a CachedMethodCaller bound to this specific instance of
33653366
the class of the cached-in-parent method.
@@ -3403,7 +3404,7 @@ class FileCache():
34033404
We assume that each :class:`FileCache` lives in its own directory.
34043405
Use **extreme** caution if you wish to break that assumption.
34053406
"""
3406-
def __init__(self, dir, prefix='', memory_cache=False):
3407+
def __init__(self, dir, prefix='', memory_cache=False) -> None:
34073408
"""
34083409
EXAMPLES::
34093410

@@ -3427,7 +3428,7 @@ class FileCache():
34273428
else:
34283429
self._cache = None
34293430
3430-
def file_list(self):
3431+
def file_list(self) -> list[str]:
34313432
"""
34323433
Return the list of files corresponding to ``self``.
34333434

@@ -3456,7 +3457,7 @@ class FileCache():
34563457
files.append(dir + f)
34573458
return files
34583459
3459-
def items(self):
3460+
def items(self) -> list[tuple[Any, Any]]:
34603461
"""
34613462
Return a list of tuples ``(k,v)`` where ``self[k] = v``.
34623463

@@ -3474,7 +3475,7 @@ class FileCache():
34743475
"""
34753476
return [(k, self[k]) for k in self]
34763477
3477-
def values(self):
3478+
def values(self) -> list:
34783479
"""
34793480
Return a list of values that are stored in ``self``.
34803481

@@ -3493,7 +3494,7 @@ class FileCache():
34933494
"""
34943495
return [self[k] for k in self]
34953496
3496-
def __iter__(self):
3497+
def __iter__(self) -> Iterator:
34973498
"""
34983499
Return a list of keys of ``self``.
34993500

@@ -3512,7 +3513,7 @@ class FileCache():
35123513
"""
35133514
return iter(self.keys())
35143515
3515-
def keys(self):
3516+
def keys(self) -> list:
35163517
"""
35173518
Return a list of keys ``k`` where ``self[k]`` is defined.
35183519

@@ -3535,7 +3536,7 @@ class FileCache():
35353536
K.append(load(f))
35363537
return K
35373538
3538-
def clear(self):
3539+
def clear(self) -> None:
35393540
"""
35403541
Clear all key, value pairs from ``self`` and unlink the associated files
35413542
from the file cache.
@@ -3561,7 +3562,7 @@ class FileCache():
35613562
for k in self:
35623563
del self[k]
35633564
3564-
def _filename(self, key):
3565+
def _filename(self, key) -> str:
35653566
"""
35663567
Compute the filename associated with a certain key.
35673568

@@ -3589,7 +3590,7 @@ class FileCache():
35893590
keystr = kwdstr + argstr
35903591
return self._dir + self._prefix + keystr
35913592
3592-
def __contains__(self, key):
3593+
def __contains__(self, key) -> bool:
35933594
"""
35943595
Return ``True`` if ``self[key]`` is defined and ``False`` otherwise.
35953596

@@ -3647,7 +3648,7 @@ class FileCache():
36473648
cache[key] = v
36483649
return v
36493650
3650-
def __setitem__(self, key, value):
3651+
def __setitem__(self, key, value) -> None:
36513652
"""
36523653
Set ``self[key] = value`` and stores both key and value on
36533654
disk.
@@ -3676,7 +3677,7 @@ class FileCache():
36763677
if self._cache is not None:
36773678
self._cache[key] = value
36783679
3679-
def __delitem__(self, key):
3680+
def __delitem__(self, key) -> None:
36803681
"""
36813682
Delete the ``key, value`` pair from ``self`` and unlink the associated
36823683
files from the file cache.
@@ -3719,7 +3720,7 @@ class DiskCachedFunction(CachedFunction):
37193720
sage: f is factor(2775)
37203721
True
37213722
"""
3722-
def __init__(self, f, dir, memory_cache=False, key=None):
3723+
def __init__(self, f, dir, memory_cache=False, key=None) -> None:
37233724
"""
37243725
EXAMPLES::
37253726

@@ -3756,7 +3757,7 @@ class disk_cached_function:
37563757
sage: foo(200)
37573758
1/200
37583759
"""
3759-
def __init__(self, dir, memory_cache=False, key=None):
3760+
def __init__(self, dir, memory_cache=False, key=None) -> None:
37603761
"""
37613762
EXAMPLES::
37623763

@@ -3775,7 +3776,7 @@ class disk_cached_function:
37753776
self._memory_cache = memory_cache
37763777
self._key = key
37773778
3778-
def __call__(self, f):
3779+
def __call__(self, f) -> DiskCachedFunction:
37793780
"""
37803781
EXAMPLES::
37813782

src/sage/misc/decorators.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,12 @@
2525
# http://www.gnu.org/licenses/
2626
# *****************************************************************************
2727

28-
from functools import (partial, update_wrapper, WRAPPER_ASSIGNMENTS,
29-
WRAPPER_UPDATES)
3028
from copy import copy
31-
32-
from sage.misc.sageinspect import (sage_getsource, sage_getsourcelines,
33-
sage_getargspec)
34-
29+
from functools import WRAPPER_ASSIGNMENTS, WRAPPER_UPDATES, partial, update_wrapper
3530
from inspect import FullArgSpec
3631

32+
from sage.misc.sageinspect import sage_getargspec, sage_getsource, sage_getsourcelines
33+
3734

3835
def sage_wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES):
3936
r"""

0 commit comments

Comments
 (0)