Skip to content

Commit 4ab6ee2

Browse files
jbrockmendeljreback
authored andcommitted
TYP: core.computation mostly (#29652)
1 parent e3e5b0d commit 4ab6ee2

File tree

8 files changed

+61
-54
lines changed

8 files changed

+61
-54
lines changed

pandas/_libs/internals.pyx

+3-3
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ cdef class BlockPlacement:
8585
return iter(self._as_array)
8686

8787
@property
88-
def as_slice(self):
88+
def as_slice(self) -> slice:
8989
cdef:
9090
slice s = self._ensure_has_slice()
9191
if s is None:
@@ -118,7 +118,7 @@ cdef class BlockPlacement:
118118
return self._as_array
119119

120120
@property
121-
def is_slice_like(self):
121+
def is_slice_like(self) -> bool:
122122
cdef:
123123
slice s = self._ensure_has_slice()
124124
return s is not None
@@ -441,7 +441,7 @@ def get_blkno_indexers(int64_t[:] blknos, bint group=True):
441441
yield blkno, result
442442

443443

444-
def get_blkno_placements(blknos, group=True):
444+
def get_blkno_placements(blknos, group: bool = True):
445445
"""
446446
447447
Parameters

pandas/_libs/sparse.pyx

+6-6
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ cdef class IntIndex(SparseIndex):
5757
return output
5858

5959
@property
60-
def nbytes(self):
60+
def nbytes(self) -> int:
6161
return self.indices.nbytes
6262

6363
def check_integrity(self):
@@ -91,7 +91,7 @@ cdef class IntIndex(SparseIndex):
9191
if not monotonic:
9292
raise ValueError("Indices must be strictly increasing")
9393

94-
def equals(self, other):
94+
def equals(self, other) -> bool:
9595
if not isinstance(other, IntIndex):
9696
return False
9797

@@ -103,7 +103,7 @@ cdef class IntIndex(SparseIndex):
103103
return same_length and same_indices
104104

105105
@property
106-
def ngaps(self):
106+
def ngaps(self) -> int:
107107
return self.length - self.npoints
108108

109109
def to_int_index(self):
@@ -348,11 +348,11 @@ cdef class BlockIndex(SparseIndex):
348348
return output
349349

350350
@property
351-
def nbytes(self):
351+
def nbytes(self) -> int:
352352
return self.blocs.nbytes + self.blengths.nbytes
353353

354354
@property
355-
def ngaps(self):
355+
def ngaps(self) -> int:
356356
return self.length - self.npoints
357357

358358
cpdef check_integrity(self):
@@ -388,7 +388,7 @@ cdef class BlockIndex(SparseIndex):
388388
if blengths[i] == 0:
389389
raise ValueError(f'Zero-length block {i}')
390390

391-
def equals(self, other):
391+
def equals(self, other) -> bool:
392392
if not isinstance(other, BlockIndex):
393393
return False
394394

pandas/_libs/writers.pyx

+1-1
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def write_csv_rows(list data, ndarray data_index,
7070

7171
@cython.boundscheck(False)
7272
@cython.wraparound(False)
73-
def convert_json_to_lines(object arr):
73+
def convert_json_to_lines(arr: object) -> str:
7474
"""
7575
replace comma separated json with line feeds, paying special attention
7676
to quotes & brackets

pandas/core/computation/align.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def _zip_axes_from_type(typ, new_axes):
3333
return axes
3434

3535

36-
def _any_pandas_objects(terms):
36+
def _any_pandas_objects(terms) -> bool:
3737
"""Check a sequence of terms for instances of PandasObject."""
3838
return any(isinstance(term.value, PandasObject) for term in terms)
3939

pandas/core/computation/engines.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,9 @@ def __init__(self, expr):
4646
self.aligned_axes = None
4747
self.result_type = None
4848

49-
def convert(self):
50-
"""Convert an expression for evaluation.
49+
def convert(self) -> str:
50+
"""
51+
Convert an expression for evaluation.
5152
5253
Defaults to return the expression as a string.
5354
"""
@@ -75,7 +76,7 @@ def evaluate(self):
7576
)
7677

7778
@property
78-
def _is_aligned(self):
79+
def _is_aligned(self) -> bool:
7980
return self.aligned_axes is not None and self.result_type is not None
8081

8182
@abc.abstractmethod
@@ -104,7 +105,7 @@ class NumExprEngine(AbstractEngine):
104105
def __init__(self, expr):
105106
super().__init__(expr)
106107

107-
def convert(self):
108+
def convert(self) -> str:
108109
return str(super().convert())
109110

110111
def _evaluate(self):

pandas/core/computation/ops.py

+17-16
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ def __new__(cls, name, env, side=None, encoding=None):
7070
return supr_new(klass)
7171

7272
def __init__(self, name, env, side=None, encoding=None):
73+
# name is a str for Term, but may be something else for subclasses
7374
self._name = name
7475
self.env = env
7576
self.side = side
@@ -79,7 +80,7 @@ def __init__(self, name, env, side=None, encoding=None):
7980
self.encoding = encoding
8081

8182
@property
82-
def local_name(self):
83+
def local_name(self) -> str:
8384
return self.name.replace(_LOCAL_TAG, "")
8485

8586
def __repr__(self) -> str:
@@ -120,7 +121,7 @@ def update(self, value):
120121
self.value = value
121122

122123
@property
123-
def is_scalar(self):
124+
def is_scalar(self) -> bool:
124125
return is_scalar(self._value)
125126

126127
@property
@@ -139,14 +140,14 @@ def type(self):
139140
return_type = type
140141

141142
@property
142-
def raw(self):
143+
def raw(self) -> str:
143144
return pprint_thing(
144145
"{0}(name={1!r}, type={2})"
145146
"".format(self.__class__.__name__, self.name, self.type)
146147
)
147148

148149
@property
149-
def is_datetime(self):
150+
def is_datetime(self) -> bool:
150151
try:
151152
t = self.type.type
152153
except AttributeError:
@@ -220,7 +221,7 @@ def return_type(self):
220221
return _result_type_many(*(term.type for term in com.flatten(self)))
221222

222223
@property
223-
def has_invalid_return_type(self):
224+
def has_invalid_return_type(self) -> bool:
224225
types = self.operand_types
225226
obj_dtype_set = frozenset([np.dtype("object")])
226227
return self.return_type == object and types - obj_dtype_set
@@ -230,11 +231,11 @@ def operand_types(self):
230231
return frozenset(term.type for term in com.flatten(self))
231232

232233
@property
233-
def is_scalar(self):
234+
def is_scalar(self) -> bool:
234235
return all(operand.is_scalar for operand in self.operands)
235236

236237
@property
237-
def is_datetime(self):
238+
def is_datetime(self) -> bool:
238239
try:
239240
t = self.return_type.type
240241
except AttributeError:
@@ -339,7 +340,7 @@ def _cast_inplace(terms, acceptable_dtypes, dtype):
339340
term.update(new_value)
340341

341342

342-
def is_term(obj):
343+
def is_term(obj) -> bool:
343344
return isinstance(obj, Term)
344345

345346

@@ -354,7 +355,7 @@ class BinOp(Op):
354355
right : Term or Op
355356
"""
356357

357-
def __init__(self, op, lhs, rhs, **kwargs):
358+
def __init__(self, op: str, lhs, rhs, **kwargs):
358359
super().__init__(op, (lhs, rhs))
359360
self.lhs = lhs
360361
self.rhs = rhs
@@ -396,7 +397,7 @@ def __call__(self, env):
396397

397398
return self.func(left, right)
398399

399-
def evaluate(self, env, engine, parser, term_type, eval_in_python):
400+
def evaluate(self, env, engine: str, parser, term_type, eval_in_python):
400401
"""
401402
Evaluate a binary operation *before* being passed to the engine.
402403
@@ -488,7 +489,7 @@ def _disallow_scalar_only_bool_ops(self):
488489
raise NotImplementedError("cannot evaluate scalar only bool ops")
489490

490491

491-
def isnumeric(dtype):
492+
def isnumeric(dtype) -> bool:
492493
return issubclass(np.dtype(dtype).type, np.number)
493494

494495

@@ -505,8 +506,8 @@ class Div(BinOp):
505506
regardless of the value of ``truediv``.
506507
"""
507508

508-
def __init__(self, lhs, rhs, truediv, *args, **kwargs):
509-
super().__init__("/", lhs, rhs, *args, **kwargs)
509+
def __init__(self, lhs, rhs, truediv: bool, **kwargs):
510+
super().__init__("/", lhs, rhs, **kwargs)
510511

511512
if not isnumeric(lhs.return_type) or not isnumeric(rhs.return_type):
512513
raise TypeError(
@@ -541,7 +542,7 @@ class UnaryOp(Op):
541542
* If no function associated with the passed operator token is found.
542543
"""
543544

544-
def __init__(self, op, operand):
545+
def __init__(self, op: str, operand):
545546
super().__init__(op, (operand,))
546547
self.operand = operand
547548

@@ -561,7 +562,7 @@ def __repr__(self) -> str:
561562
return pprint_thing("{0}({1})".format(self.op, self.operand))
562563

563564
@property
564-
def return_type(self):
565+
def return_type(self) -> np.dtype:
565566
operand = self.operand
566567
if operand.return_type == np.dtype("bool"):
567568
return np.dtype("bool")
@@ -588,7 +589,7 @@ def __repr__(self) -> str:
588589

589590

590591
class FuncNode:
591-
def __init__(self, name):
592+
def __init__(self, name: str):
592593
from pandas.core.computation.check import _NUMEXPR_INSTALLED, _NUMEXPR_VERSION
593594

594595
if name not in _mathops or (

pandas/core/computation/pytables.py

+15-11
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import ast
44
from functools import partial
5+
from typing import Optional
56

67
import numpy as np
78

@@ -129,12 +130,12 @@ def conform(self, rhs):
129130
return rhs
130131

131132
@property
132-
def is_valid(self):
133+
def is_valid(self) -> bool:
133134
""" return True if this is a valid field """
134135
return self.lhs in self.queryables
135136

136137
@property
137-
def is_in_table(self):
138+
def is_in_table(self) -> bool:
138139
""" return True if this is a valid column name for generation (e.g. an
139140
actual column in the table) """
140141
return self.queryables.get(self.lhs) is not None
@@ -154,12 +155,12 @@ def metadata(self):
154155
""" the metadata of my field """
155156
return getattr(self.queryables.get(self.lhs), "metadata", None)
156157

157-
def generate(self, v):
158+
def generate(self, v) -> str:
158159
""" create and return the op string for this TermValue """
159160
val = v.tostring(self.encoding)
160161
return "({lhs} {op} {val})".format(lhs=self.lhs, op=self.op, val=val)
161162

162-
def convert_value(self, v):
163+
def convert_value(self, v) -> "TermValue":
163164
""" convert the expression that is in the term to something that is
164165
accepted by pytables """
165166

@@ -279,7 +280,7 @@ def evaluate(self):
279280

280281
return self
281282

282-
def generate_filter_op(self, invert=False):
283+
def generate_filter_op(self, invert: bool = False):
283284
if (self.op == "!=" and not invert) or (self.op == "==" and invert):
284285
return lambda axis, vals: ~axis.isin(vals)
285286
else:
@@ -505,7 +506,7 @@ class Expr(expr.Expr):
505506
"major_axis>=20130101"
506507
"""
507508

508-
def __init__(self, where, queryables=None, encoding=None, scope_level=0):
509+
def __init__(self, where, queryables=None, encoding=None, scope_level: int = 0):
509510

510511
where = _validate_where(where)
511512

@@ -520,18 +521,21 @@ def __init__(self, where, queryables=None, encoding=None, scope_level=0):
520521

521522
if isinstance(where, Expr):
522523
local_dict = where.env.scope
523-
where = where.expr
524+
_where = where.expr
524525

525526
elif isinstance(where, (list, tuple)):
527+
where = list(where)
526528
for idx, w in enumerate(where):
527529
if isinstance(w, Expr):
528530
local_dict = w.env.scope
529531
else:
530532
w = _validate_where(w)
531533
where[idx] = w
532-
where = " & ".join(map("({})".format, com.flatten(where))) # noqa
534+
_where = " & ".join(map("({})".format, com.flatten(where)))
535+
else:
536+
_where = where
533537

534-
self.expr = where
538+
self.expr = _where
535539
self.env = Scope(scope_level + 1, local_dict=local_dict)
536540

537541
if queryables is not None and isinstance(self.expr, str):
@@ -574,7 +578,7 @@ def evaluate(self):
574578
class TermValue:
575579
""" hold a term value the we use to construct a condition/filter """
576580

577-
def __init__(self, value, converted, kind):
581+
def __init__(self, value, converted, kind: Optional[str]):
578582
self.value = value
579583
self.converted = converted
580584
self.kind = kind
@@ -593,7 +597,7 @@ def tostring(self, encoding):
593597
return self.converted
594598

595599

596-
def maybe_expression(s):
600+
def maybe_expression(s) -> bool:
597601
""" loose checking if s is a pytables-acceptable expression """
598602
if not isinstance(s, str):
599603
return False

0 commit comments

Comments
 (0)