Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rule C416 broke some pandas code #4491

Open
wlach opened this issue May 18, 2023 · 4 comments
Open

Rule C416 broke some pandas code #4491

wlach opened this issue May 18, 2023 · 4 comments
Labels
bug Something isn't working

Comments

@wlach
Copy link

wlach commented May 18, 2023

This snippit:

import pandas as pd
obj = { k: v for k,v in pd.DataFrame.from_records([], columns=["foo", "bar", "baz"]).groupby("foo")}

Is rewritten to the following using the C416 rule (no unnecessary comprehensions):

import pandas pd
obj = dict(pd.DataFrame.from_records([], columns=["foo", "bar", "baz"]).groupby("foo"))

However that generates a TypeError when I run it. I filed a bug about this upstream (see pandas-dev/pandas#53287) but it makes me wonder if this rule is safe to apply. Current using ruff 0.0.262.

@charliermarsh
Copy link
Member

Huh, interesting. It's not immediately clear to me why / how those are different.

@charliermarsh charliermarsh added the bug Something isn't working label May 18, 2023
@edgarrmondragon
Copy link
Contributor

edgarrmondragon commented May 18, 2023

FWIW it's fixed by wrapping the DataFrameGroupBy object with iter:

import pandas as pd
obj = dict(iter(pd.DataFrame.from_records([], columns=["foo", "bar", "baz"]).groupby("foo")))

or using the splat * operator

import pandas as pd
obj = dict(*pd.DataFrame.from_records([], columns=["foo", "bar", "baz"]).groupby("foo"))

@Charlie-XIAO
Copy link

The splat * operator does not work in general (only works when empty). iter() works because DataFrameGroupBy.__iter__() is a public method that returns a generator yielding sequence of (name, subsetted object) for each group.

@zanieb
Copy link
Member

zanieb commented May 18, 2023

Interesting...

Thanks for reporting this issue. I looked online and apparently Python's dict() method checks for existence of the .keys() method.

https://stackoverflow.com/questions/40667093/what-is-a-mapping-object-according-to-dict-type

Unfortunately, in this case obj.keys returns a str, which is not callable.

ref pandas-dev/pandas#53287 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

5 participants