Skip to content

Commit 589bd6d

Browse files
authored
Art resizer typings v2 (#5734)
A rebased & amended version of #4649. I left a FIXME note regarding a cleanup that I feel should be done at some point, but that is out-of-scope here when just adding initial typings.
2 parents 0379f68 + 26008eb commit 589bd6d

File tree

2 files changed

+317
-88
lines changed

2 files changed

+317
-88
lines changed

beets/util/__init__.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
Any,
4141
AnyStr,
4242
Callable,
43+
Generic,
4344
Iterable,
4445
NamedTuple,
4546
TypeVar,
@@ -1041,6 +1042,53 @@ def __get__(self, instance, owner):
10411042
return self.cache[owner]
10421043

10431044

1045+
class LazySharedInstance(Generic[T]):
1046+
"""A descriptor that provides access to a lazily-created shared instance of
1047+
the containing class, while calling the class constructor to construct a
1048+
new object works as usual.
1049+
1050+
```
1051+
ID: int = 0
1052+
1053+
class Foo:
1054+
def __init__():
1055+
global ID
1056+
1057+
self.id = ID
1058+
ID += 1
1059+
1060+
def func(self):
1061+
print(self.id)
1062+
1063+
shared: LazySharedInstance[Foo] = LazySharedInstance()
1064+
1065+
a0 = Foo()
1066+
a1 = Foo.shared
1067+
a2 = Foo()
1068+
a3 = Foo.shared
1069+
1070+
a0.func() # 0
1071+
a1.func() # 1
1072+
a2.func() # 2
1073+
a3.func() # 1
1074+
```
1075+
"""
1076+
1077+
_instance: T | None = None
1078+
1079+
def __get__(self, instance: T | None, owner: type[T]) -> T:
1080+
if instance is not None:
1081+
raise RuntimeError(
1082+
"shared instances must be obtained from the class property, "
1083+
"not an instance"
1084+
)
1085+
1086+
if self._instance is None:
1087+
self._instance = owner()
1088+
1089+
return self._instance
1090+
1091+
10441092
def get_module_tempdir(module: str) -> Path:
10451093
"""Return the temporary directory for the given module.
10461094

0 commit comments

Comments
 (0)