Use object instead of Any for labels() parameters#1186
Conversation
9c154a6 to
49c6c19
Compare
|
Hello @csmarchbanks 👋 Following the CONTRIBUTING.md, I should ping you to get your review for a trivial change. This is just a type change from |
Signed-off-by: Grégoire Deveaux <gregoire.deveaux@gitguardian.com>
49c6c19 to
757abe8
Compare
csmarchbanks
left a comment
There was a problem hiding this comment.
Thanks for the PR!
I don't feel like it helps all that much though, I don't love introducing another variable just to appease the typechecker when Any still works (or will raise) today. What's the goal of reducing Any usage?
|
Thanks for looking into it!
The name Any may be a bit counter intuitive, but it's usage is meant to say "I don't know, I want to opt out from type checking here" and not just "this can be of any type". When you want the type checker to look at the code while making sure it can handle any type, then the proper type to use is
That's actually exactly what happened to In our case, we have introduced type checking on a big code base (>1M lines). We can't type everything at once but we need a metric to be able to follow our progress. mypy reports help us do this by giving statistics per lines and modules for what it's able to infer. Lines using the Any "escape hatch" intruduce "type unsafety" (by mypy definition). Those are lines where mypy is in effect useless. Since we want to enforce typing, measuring that this number goes down is highly correlated to our code being actually type safe.
Me neither. You can say it's just to appease the typechecker but one could say it's to fix types in this method.
We may be able to keep type checking and handle those problems via casts or ignored errors but I'm not sure it's better than introducing a variable. From my perspective, it looks like we can easily remove "type unsafety" from But you're the maintainer and it could make sense to consciously choose type unsafety in some parts of the lib. We can do some kind of wrapper on our side to confine the Prometheus client type unsafety part. I hope this is clear and not too long 😄 |
I'm working on a project where we try to reduce lines flagged as
Anyby mypy line precision report.The type of
labels()parameters isAny, reducing the whole line asAny(mypy takes the worst of the line typing for its report).Using
objecthere looks like the right choice.From https://mypy.readthedocs.io/en/stable/kinds_of_types.html#the-any-type
I first thought it would even be
strsince it's the natural type of labels, butlabels()transforms parameters to strings automatically (labelvalues = tuple(str(labelkwargs[l]) for l in self._labelnames)andlabelvalues = tuple(str(l) for l in labelvalues)).So we mean "anything that can be
stred",objectlooks like a good candidate for that type.Note: I had to introduce
str_labelvaluesto comply withmypy(since nowlabelvalueshas typetuple[object, ...]which is not compatible withtuple[str, ...]).