Skip to content

Commit

Permalink
issue 48855 enable pylint C-type "disallowed-name " warning (#49379)
Browse files Browse the repository at this point in the history
* remove from exclusions + cleanup

* try foo variation, instead

* revert change + exclude from linting

* revert + exclude from linting

* revert + exclude fron linting

* more descriptive names

* try assigning to itself

* more test clean-up

* try reverting with exclusion

* more clean-up

* revert
  • Loading branch information
stellalin7 authored Nov 2, 2022
1 parent 6526e93 commit 7ccac68
Show file tree
Hide file tree
Showing 21 changed files with 87 additions and 78 deletions.
2 changes: 1 addition & 1 deletion asv_bench/benchmarks/attrs_caching.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def setup(self):
self.cur_index = self.df.index

def time_get_index(self):
self.foo = self.df.index
self.df.index

def time_set_index(self):
self.df.index = self.cur_index
Expand Down
2 changes: 1 addition & 1 deletion pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -2902,7 +2902,7 @@ def set_properties(self, subset: Subset | None = None, **kwargs) -> Styler:
return self.applymap(lambda x: values, subset=subset)

@Substitution(subset=subset)
def bar(
def bar( # pylint: disable=disallowed-name
self,
subset: Subset | None = None,
axis: Axis | None = 0,
Expand Down
4 changes: 3 additions & 1 deletion pandas/plotting/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1131,7 +1131,9 @@ def line(self, x=None, y=None, **kwargs) -> PlotAccessor:
)
@Substitution(kind="bar")
@Appender(_bar_or_line_doc)
def bar(self, x=None, y=None, **kwargs) -> PlotAccessor:
def bar( # pylint: disable=disallowed-name
self, x=None, y=None, **kwargs
) -> PlotAccessor:
"""
Vertical bar plot.
Expand Down
10 changes: 5 additions & 5 deletions pandas/tests/apply/test_frame_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -1516,18 +1516,18 @@ def test_aggregation_func_column_order():
columns=("att1", "att2", "att3"),
)

def foo(s):
def sum_div2(s):
return s.sum() / 2

aggs = ["sum", foo, "count", "min"]
aggs = ["sum", sum_div2, "count", "min"]
result = df.agg(aggs)
expected = DataFrame(
{
"att1": [21.0, 10.5, 6.0, 1.0],
"att2": [18.0, 9.0, 6.0, 0.0],
"att3": [17.0, 8.5, 6.0, 0.0],
},
index=["sum", "foo", "count", "min"],
index=["sum", "sum_div2", "count", "min"],
)
tm.assert_frame_equal(result, expected)

Expand All @@ -1548,13 +1548,13 @@ def test_nuisance_depr_passes_through_warnings():
# sure if some other warnings were raised, they get passed through to
# the user.

def foo(x):
def expected_warning(x):
warnings.warn("Hello, World!")
return x.sum()

df = DataFrame({"a": [1, 2, 3]})
with tm.assert_produces_warning(UserWarning, match="Hello, World!"):
df.agg([foo])
df.agg([expected_warning])


def test_apply_type():
Expand Down
30 changes: 15 additions & 15 deletions pandas/tests/base/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,19 +43,19 @@ def constructor(request):

class TestPandasDelegate:
class Delegator:
_properties = ["foo"]
_methods = ["bar"]
_properties = ["prop"]
_methods = ["test_method"]

def _set_foo(self, value):
self.foo = value
def _set_prop(self, value):
self.prop = value

def _get_foo(self):
return self.foo
def _get_prop(self):
return self.prop

foo = property(_get_foo, _set_foo, doc="foo property")
prop = property(_get_prop, _set_prop, doc="foo property")

def bar(self, *args, **kwargs):
"""a test bar method"""
def test_method(self, *args, **kwargs):
"""a test method"""

class Delegate(PandasDelegate, PandasObject):
def __init__(self, obj) -> None:
Expand All @@ -77,17 +77,17 @@ def test_invalid_delegation(self):

delegate = self.Delegate(self.Delegator())

msg = "You cannot access the property foo"
msg = "You cannot access the property prop"
with pytest.raises(TypeError, match=msg):
delegate.foo
delegate.prop

msg = "The property foo cannot be set"
msg = "The property prop cannot be set"
with pytest.raises(TypeError, match=msg):
delegate.foo = 5
delegate.prop = 5

msg = "You cannot access the property foo"
msg = "You cannot access the property prop"
with pytest.raises(TypeError, match=msg):
delegate.foo()
delegate.prop()

@pytest.mark.skipif(PYPY, reason="not relevant for PyPy")
def test_memory_usage(self):
Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/dtypes/test_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,16 +203,16 @@ def test_is_list_like_disallow_sets(maybe_list_like):
def test_is_list_like_recursion():
# GH 33721
# interpreter would crash with SIGABRT
def foo():
def list_like():
inference.is_list_like([])
foo()
list_like()

rec_limit = sys.getrecursionlimit()
try:
# Limit to avoid stack overflow on Windows CI
sys.setrecursionlimit(100)
with tm.external_error_raised(RecursionError):
foo()
list_like()
finally:
sys.setrecursionlimit(rec_limit)

Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/frame/test_subclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,11 +138,11 @@ def test_subclass_attr_err_propagation(self):
# GH 11808
class A(DataFrame):
@property
def bar(self):
def nonexistence(self):
return self.i_dont_exist

with pytest.raises(AttributeError, match=".*i_dont_exist.*"):
A().bar
A().nonexistence

def test_subclass_align(self):
# GH 12983
Expand Down
14 changes: 7 additions & 7 deletions pandas/tests/groupby/aggregate/test_aggregate.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,15 +283,15 @@ def test_aggregate_item_by_item(df):

aggfun_0 = lambda ser: ser.size
result = grouped.agg(aggfun_0)
foo = (df.A == "foo").sum()
bar = (df.A == "bar").sum()
foosum = (df.A == "foo").sum()
barsum = (df.A == "bar").sum()
K = len(result.columns)

# GH5782
exp = Series(np.array([foo] * K), index=list("BCD"), name="foo")
exp = Series(np.array([foosum] * K), index=list("BCD"), name="foo")
tm.assert_series_equal(result.xs("foo"), exp)

exp = Series(np.array([bar] * K), index=list("BCD"), name="bar")
exp = Series(np.array([barsum] * K), index=list("BCD"), name="bar")
tm.assert_almost_equal(result.xs("bar"), exp)

def aggfun_1(ser):
Expand Down Expand Up @@ -417,10 +417,10 @@ def test_more_flexible_frame_multi_function(df):
expected = grouped.aggregate({"C": np.mean, "D": [np.mean, np.std]})
tm.assert_frame_equal(result, expected)

def foo(x):
def numpymean(x):
return np.mean(x)

def bar(x):
def numpystd(x):
return np.std(x, ddof=1)

# this uses column selection & renaming
Expand All @@ -430,7 +430,7 @@ def bar(x):
grouped.aggregate(d)

# But without renaming, these functions are OK
d = {"C": [np.mean], "D": [foo, bar]}
d = {"C": [np.mean], "D": [numpymean, numpystd]}
grouped.aggregate(d)


Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/groupby/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1616,7 +1616,7 @@ def freduce(group):
assert group.name is not None
return group.sum()

def foo(x):
def freducex(x):
return freduce(x)

grouped = df.groupby(grouper, group_keys=False)
Expand All @@ -1629,7 +1629,7 @@ def foo(x):

grouped["C"].apply(f)
grouped["C"].aggregate(freduce)
grouped["C"].aggregate([freduce, foo])
grouped["C"].aggregate([freduce, freducex])
grouped["C"].transform(f)


Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/indexes/multi/test_integrity.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,14 +233,14 @@ def test_level_setting_resets_attributes():

def test_rangeindex_fallback_coercion_bug():
# GH 12893
foo = pd.DataFrame(np.arange(100).reshape((10, 10)))
bar = pd.DataFrame(np.arange(100).reshape((10, 10)))
df = pd.concat({"foo": foo.stack(), "bar": bar.stack()}, axis=1)
df1 = pd.DataFrame(np.arange(100).reshape((10, 10)))
df2 = pd.DataFrame(np.arange(100).reshape((10, 10)))
df = pd.concat({"df1": df1.stack(), "df2": df2.stack()}, axis=1)
df.index.names = ["fizz", "buzz"]

str(df)
expected = pd.DataFrame(
{"bar": np.arange(100), "foo": np.arange(100)},
{"df2": np.arange(100), "df1": np.arange(100)},
index=MultiIndex.from_product([range(10), range(10)], names=["fizz", "buzz"]),
)
tm.assert_frame_equal(df, expected, check_like=True)
Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/io/formats/style/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -653,10 +653,10 @@ def test_apply_dataframe_return(self, index, columns):
)
@pytest.mark.parametrize("axis", [0, 1])
def test_apply_subset(self, slice_, axis, df):
def h(x, foo="bar"):
return Series(f"color: {foo}", index=x.index, name=x.name)
def h(x, color="bar"):
return Series(f"color: {color}", index=x.index, name=x.name)

result = df.style.apply(h, axis=axis, subset=slice_, foo="baz")._compute().ctx
result = df.style.apply(h, axis=axis, subset=slice_, color="baz")._compute().ctx
expected = {
(r, c): [("color", "baz")]
for r, row in enumerate(df.index)
Expand Down
24 changes: 12 additions & 12 deletions pandas/tests/io/test_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -2181,26 +2181,26 @@ def test_connectable_issue_example(self):
# https://github.com/pandas-dev/pandas/issues/10104
from sqlalchemy.engine import Engine

def foo(connection):
def test_select(connection):
query = "SELECT test_foo_data FROM test_foo_data"
return sql.read_sql_query(query, con=connection)

def bar(connection, data):
def test_append(connection, data):
data.to_sql(name="test_foo_data", con=connection, if_exists="append")

def baz(conn):
def test_connectable(conn):
# https://github.com/sqlalchemy/sqlalchemy/commit/
# 00b5c10846e800304caa86549ab9da373b42fa5d#r48323973
foo_data = foo(conn)
bar(conn, foo_data)
foo_data = test_select(conn)
test_append(conn, foo_data)

def main(connectable):
if isinstance(connectable, Engine):
with connectable.connect() as conn:
with conn.begin():
baz(conn)
test_connectable(conn)
else:
baz(connectable)
test_connectable(connectable)

assert (
DataFrame({"test_foo_data": [0, 1, 2]}).to_sql("test_foo_data", self.conn)
Expand Down Expand Up @@ -2373,21 +2373,21 @@ def test_row_object_is_named_tuple(self):
class Test(BaseModel):
__tablename__ = "test_frame"
id = Column(Integer, primary_key=True)
foo = Column(String(50))
string_column = Column(String(50))

BaseModel.metadata.create_all(self.conn)
Session = sessionmaker(bind=self.conn)
with Session() as session:
df = DataFrame({"id": [0, 1], "foo": ["hello", "world"]})
df = DataFrame({"id": [0, 1], "string_column": ["hello", "world"]})
assert (
df.to_sql("test_frame", con=self.conn, index=False, if_exists="replace")
== 2
)
session.commit()
foo = session.query(Test.id, Test.foo)
df = DataFrame(foo)
test_query = session.query(Test.id, Test.string_column)
df = DataFrame(test_query)

assert list(df.columns) == ["id", "foo"]
assert list(df.columns) == ["id", "string_column"]


class _TestMySQLAlchemy:
Expand Down
8 changes: 5 additions & 3 deletions pandas/tests/resample/test_period_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -605,9 +605,11 @@ def test_resample_with_dst_time_change(self):

def test_resample_bms_2752(self):
# GH2753
foo = Series(index=pd.bdate_range("20000101", "20000201"), dtype=np.float64)
res1 = foo.resample("BMS").mean()
res2 = foo.resample("BMS").mean().resample("B").mean()
timeseries = Series(
index=pd.bdate_range("20000101", "20000201"), dtype=np.float64
)
res1 = timeseries.resample("BMS").mean()
res2 = timeseries.resample("BMS").mean().resample("B").mean()
assert res1.index[0] == Timestamp("20000103")
assert res1.index[0] == res2.index[0]

Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/reshape/concat/test_empty.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ class TestEmptyConcat:
def test_handle_empty_objects(self, sort):
df = DataFrame(np.random.randn(10, 4), columns=list("abcd"))

baz = df[:5].copy()
baz["foo"] = "bar"
dfcopy = df[:5].copy()
dfcopy["foo"] = "bar"
empty = df[5:5]

frames = [baz, empty, empty, df[5:]]
frames = [dfcopy, empty, empty, df[5:]]
concatted = concat(frames, axis=0, sort=sort)

expected = df.reindex(columns=["a", "b", "c", "d", "foo"])
Expand Down
18 changes: 12 additions & 6 deletions pandas/tests/reshape/concat/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,24 +120,30 @@ def test_concat_series_name_npscalar_tuple(self, s1name, s2name):

def test_concat_series_partial_columns_names(self):
# GH10698
foo = Series([1, 2], name="foo")
bar = Series([1, 2])
baz = Series([4, 5])
named_series = Series([1, 2], name="foo")
unnamed_series1 = Series([1, 2])
unnamed_series2 = Series([4, 5])

result = concat([foo, bar, baz], axis=1)
result = concat([named_series, unnamed_series1, unnamed_series2], axis=1)
expected = DataFrame(
{"foo": [1, 2], 0: [1, 2], 1: [4, 5]}, columns=["foo", 0, 1]
)
tm.assert_frame_equal(result, expected)

result = concat([foo, bar, baz], axis=1, keys=["red", "blue", "yellow"])
result = concat(
[named_series, unnamed_series1, unnamed_series2],
axis=1,
keys=["red", "blue", "yellow"],
)
expected = DataFrame(
{"red": [1, 2], "blue": [1, 2], "yellow": [4, 5]},
columns=["red", "blue", "yellow"],
)
tm.assert_frame_equal(result, expected)

result = concat([foo, bar, baz], axis=1, ignore_index=True)
result = concat(
[named_series, unnamed_series1, unnamed_series2], axis=1, ignore_index=True
)
expected = DataFrame({0: [1, 2], 1: [1, 2], 2: [4, 5]})
tm.assert_frame_equal(result, expected)

Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/reshape/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2109,9 +2109,9 @@ def test_pivot_table_no_column_raises(self):
def agg(arr):
return np.mean(arr)

foo = DataFrame({"X": [0, 0, 1, 1], "Y": [0, 1, 0, 1], "Z": [10, 20, 30, 40]})
df = DataFrame({"X": [0, 0, 1, 1], "Y": [0, 1, 0, 1], "Z": [10, 20, 30, 40]})
with pytest.raises(KeyError, match="notpresent"):
foo.pivot_table("notpresent", "X", "Y", aggfunc=agg)
df.pivot_table("notpresent", "X", "Y", aggfunc=agg)

def test_pivot_table_multiindex_columns_doctest_case(self):
# The relevant characteristic is that the call
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/util/test_deprecate_nonkeyword_arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def test_i_signature():

class Foo:
@deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "bar"])
def baz(self, bar=None, foobar=None):
def baz(self, bar=None, foobar=None): # pylint: disable=disallowed-name
...


Expand Down
Loading

0 comments on commit 7ccac68

Please sign in to comment.