Skip to content

Commit 3f25405

Browse files
author
MomIsBestFriend
committed
Some code cleanups
1 parent 761bceb commit 3f25405

File tree

4 files changed

+45
-46
lines changed

4 files changed

+45
-46
lines changed

pandas/core/base.py

+34-36
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
Base and utility classes for pandas objects.
33
"""
4+
45
import builtins
56
import textwrap
67
from typing import Dict, FrozenSet, List, Optional, Union
@@ -45,11 +46,15 @@
4546

4647

4748
class PandasObject(DirNamesMixin):
48-
"""baseclass for various pandas objects"""
49+
"""
50+
Baseclass for various pandas objects.
51+
"""
4952

5053
@property
5154
def _constructor(self):
52-
"""class constructor (for this class it's just `__class__`"""
55+
"""
56+
Class constructor (for this class it's just `__class__`.
57+
"""
5358
return type(self)
5459

5560
def __repr__(self) -> str:
@@ -77,16 +82,14 @@ def __sizeof__(self):
7782
"""
7883
if hasattr(self, "memory_usage"):
7984
mem = self.memory_usage(deep=True)
80-
if not is_scalar(mem):
81-
mem = mem.sum()
82-
return int(mem)
85+
return int(mem if is_scalar(mem) else mem.sum())
8386

84-
# no memory_usage attribute, so fall back to
85-
# object's 'sizeof'
87+
# no memory_usage attribute, so fall back to object's 'sizeof'
8688
return super().__sizeof__()
8789

8890
def _ensure_type(self: T, obj) -> T:
89-
"""Ensure that an object has same type as self.
91+
"""
92+
Ensure that an object has same type as self.
9093
9194
Used by type checkers.
9295
"""
@@ -95,7 +98,8 @@ def _ensure_type(self: T, obj) -> T:
9598

9699

97100
class NoNewAttributesMixin:
98-
"""Mixin which prevents adding new attributes.
101+
"""
102+
Mixin which prevents adding new attributes.
99103
100104
Prevents additional attributes via xxx.attribute = "something" after a
101105
call to `self.__freeze()`. Mainly used to prevent the user from using
@@ -106,7 +110,9 @@ class NoNewAttributesMixin:
106110
"""
107111

108112
def _freeze(self):
109-
"""Prevents setting additional attributes"""
113+
"""
114+
Prevents setting additional attributes.
115+
"""
110116
object.__setattr__(self, "__frozen", True)
111117

112118
# prevent adding any attribute via s.xxx.new_attribute = ...
@@ -180,14 +186,12 @@ class SelectionMixin:
180186
@property
181187
def _selection_name(self):
182188
"""
183-
return a name for myself; this would ideally be called
184-
the 'name' property, but we cannot conflict with the
185-
Series.name property which can be set
189+
Return a name for myself;
190+
191+
This would ideally be called the 'name' property,
192+
but we cannot conflict with the Series.name property which can be set.
186193
"""
187-
if self._selection is None:
188-
return None # 'result'
189-
else:
190-
return self._selection
194+
return self._selection
191195

192196
@property
193197
def _selection_list(self):
@@ -199,7 +203,6 @@ def _selection_list(self):
199203

200204
@cache_readonly
201205
def _selected_obj(self):
202-
203206
if self._selection is None or isinstance(self.obj, ABCSeries):
204207
return self.obj
205208
else:
@@ -246,12 +249,11 @@ def _gotitem(self, key, ndim: int, subset=None):
246249
247250
Parameters
248251
----------
249-
key : string / list of selections
252+
key : str / list of selections
250253
ndim : 1,2
251254
requested ndim of result
252255
subset : object, default None
253256
subset to act on
254-
255257
"""
256258
raise AbstractMethodError(self)
257259

@@ -266,7 +268,6 @@ def _try_aggregate_string_function(self, arg: str, *args, **kwargs):
266268
- try to find a function (or attribute) on ourselves
267269
- try to find a numpy function
268270
- raise
269-
270271
"""
271272
assert isinstance(arg, str)
272273

@@ -585,7 +586,6 @@ def _shallow_copy(self, obj, **kwargs):
585586
"""
586587
return a new object with the replacement attributes
587588
"""
588-
589589
if isinstance(obj, self._constructor):
590590
obj = obj.obj
591591
for attr in self._attributes:
@@ -669,8 +669,7 @@ def item(self):
669669

670670
if len(self) == 1:
671671
return next(iter(self))
672-
else:
673-
raise ValueError("can only convert an array of size 1 to a Python scalar")
672+
raise ValueError("can only convert an array of size 1 to a Python scalar")
674673

675674
@property
676675
def nbytes(self) -> int:
@@ -735,7 +734,6 @@ def array(self) -> ExtensionArray:
735734
736735
Examples
737736
--------
738-
739737
For regular NumPy types like int, and float, a PandasArray
740738
is returned.
741739
@@ -851,12 +849,11 @@ def to_numpy(self, dtype=None, copy=False, na_value=lib.no_default, **kwargs):
851849
"""
852850
if is_extension_array_dtype(self.dtype):
853851
return self.array.to_numpy(dtype, copy=copy, na_value=na_value, **kwargs)
854-
else:
855-
if kwargs:
856-
msg = "to_numpy() got an unexpected keyword argument '{}'".format(
857-
list(kwargs.keys())[0]
858-
)
859-
raise TypeError(msg)
852+
elif kwargs:
853+
bad_keys = list(kwargs.keys())[0]
854+
raise TypeError(
855+
f"to_numpy() got an unexpected keyword argument '{bad_keys}'"
856+
)
860857

861858
result = np.asarray(self._values, dtype=dtype)
862859
# TODO(GH-24345): Avoid potential double copy
@@ -1076,7 +1073,9 @@ def _reduce(
10761073
filter_type=None,
10771074
**kwds,
10781075
):
1079-
""" perform the reduction type operation if we can """
1076+
"""
1077+
Perform the reduction type operation if we can.
1078+
"""
10801079
func = getattr(self, name, None)
10811080
if func is None:
10821081
raise TypeError(
@@ -1103,9 +1102,7 @@ def _map_values(self, mapper, na_action=None):
11031102
The output of the mapping function applied to the index.
11041103
If the function returns a tuple with more than one element
11051104
a MultiIndex will be returned.
1106-
11071105
"""
1108-
11091106
# we can fastpath dict/Series to an efficient map
11101107
# as we know that we are not going to have to yield
11111108
# python types
@@ -1341,7 +1338,9 @@ def is_monotonic(self) -> bool:
13411338

13421339
@property
13431340
def is_monotonic_increasing(self) -> bool:
1344-
"""alias for is_monotonic"""
1341+
"""
1342+
Alias for is_monotonic.
1343+
"""
13451344
# mypy complains if we alias directly
13461345
return self.is_monotonic
13471346

@@ -1455,7 +1454,6 @@ def factorize(self, sort=False, na_sentinel=-1):
14551454
14561455
Examples
14571456
--------
1458-
14591457
>>> x = pd.Series([1, 2, 3])
14601458
>>> x
14611459
0 1

pandas/core/frame.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -874,8 +874,8 @@ def style(self) -> "Styler":
874874
polar bear 22000
875875
koala marsupial 80000
876876
>>> for label, content in df.items():
877-
... print('label:', label)
878-
... print('content:', content, sep='\n')
877+
... print(f'label: {label}')
878+
... print(f'content: {content}', sep='\n')
879879
...
880880
label: species
881881
content:

pandas/io/excel/_pyxlsb.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,12 @@
88

99
class _PyxlsbReader(_BaseExcelReader):
1010
def __init__(self, filepath_or_buffer: FilePathOrBuffer):
11-
"""Reader using pyxlsb engine.
11+
"""
12+
Reader using pyxlsb engine.
1213
1314
Parameters
14-
__________
15-
filepath_or_buffer: string, path object, or Workbook
15+
----------
16+
filepath_or_buffer: str, path object, or Workbook
1617
Object to be parsed.
1718
"""
1819
import_optional_dependency("pyxlsb")
@@ -29,7 +30,7 @@ def _workbook_class(self):
2930
def load_workbook(self, filepath_or_buffer: FilePathOrBuffer):
3031
from pyxlsb import open_workbook
3132

32-
# Todo: hack in buffer capability
33+
# TODO: hack in buffer capability
3334
# This might need some modifications to the Pyxlsb library
3435
# Actual work for opening it is in xlsbpackage.py, line 20-ish
3536

@@ -48,7 +49,7 @@ def get_sheet_by_index(self, index: int):
4849
return self.book.get_sheet(index + 1)
4950

5051
def _convert_cell(self, cell, convert_float: bool) -> Scalar:
51-
# Todo: there is no way to distinguish between floats and datetimes in pyxlsb
52+
# TODO: there is no way to distinguish between floats and datetimes in pyxlsb
5253
# This means that there is no way to read datetime types from an xlsb file yet
5354
if cell.v is None:
5455
return "" # Prevents non-named columns from not showing up as Unnamed: i

pandas/util/_test_decorators.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -77,16 +77,16 @@ def safe_import(mod_name: str, min_version: Optional[str] = None):
7777

7878

7979
# TODO:
80-
# remove when gh-24839 is fixed; this affects numpy 1.16
81-
# and pytables 3.4.4
80+
# remove when gh-24839 is fixed.
81+
# this affects numpy 1.16 and pytables 3.4.4
8282
tables = safe_import("tables")
8383
xfail_non_writeable = pytest.mark.xfail(
8484
tables
8585
and LooseVersion(np.__version__) >= LooseVersion("1.16")
8686
and LooseVersion(tables.__version__) < LooseVersion("3.5.1"),
8787
reason=(
8888
"gh-25511, gh-24839. pytables needs a "
89-
"release beyong 3.4.4 to support numpy 1.16x"
89+
"release beyond 3.4.4 to support numpy 1.16.x"
9090
),
9191
)
9292

0 commit comments

Comments
 (0)