Skip to content

Commit 51ce777

Browse files
xhochyjreback
authored andcommitted
TYP: Fix chainmap typing for mypy 0.740+ (#30680)
1 parent 66b4dbc commit 51ce777

File tree

2 files changed

+19
-9
lines changed

2 files changed

+19
-9
lines changed

pandas/compat/chainmap.py

+18-8
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,33 @@
1-
from collections import ChainMap
1+
from typing import ChainMap, MutableMapping, TypeVar, cast
22

3+
_KT = TypeVar("_KT")
4+
_VT = TypeVar("_VT")
35

4-
class DeepChainMap(ChainMap):
5-
def __setitem__(self, key, value):
6+
7+
class DeepChainMap(ChainMap[_KT, _VT]):
8+
"""Variant of ChainMap that allows direct updates to inner scopes.
9+
10+
Only works when all passed mapping are mutable.
11+
"""
12+
13+
def __setitem__(self, key: _KT, value: _VT) -> None:
614
for mapping in self.maps:
7-
if key in mapping:
8-
mapping[key] = value
15+
mutable_mapping = cast(MutableMapping[_KT, _VT], mapping)
16+
if key in mutable_mapping:
17+
mutable_mapping[key] = value
918
return
10-
self.maps[0][key] = value
19+
cast(MutableMapping[_KT, _VT], self.maps[0])[key] = value
1120

12-
def __delitem__(self, key):
21+
def __delitem__(self, key: _KT) -> None:
1322
"""
1423
Raises
1524
------
1625
KeyError
1726
If `key` doesn't exist.
1827
"""
1928
for mapping in self.maps:
29+
mutable_mapping = cast(MutableMapping[_KT, _VT], mapping)
2030
if key in mapping:
21-
del mapping[key]
31+
del mutable_mapping[key]
2232
return
2333
raise KeyError(key)

pandas/core/computation/pytables.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -533,7 +533,7 @@ def __init__(
533533
self._visitor = None
534534

535535
# capture the environment if needed
536-
local_dict = DeepChainMap()
536+
local_dict: DeepChainMap[Any, Any] = DeepChainMap()
537537

538538
if isinstance(where, PyTablesExpr):
539539
local_dict = where.env.scope

0 commit comments

Comments
 (0)