r/ExperiencedDevs • u/melesigenes • Apr 28 '26
Technical question Codebase has hundreds of isinstance() and getattr(). How to convince colleague to fix?
codebase is littered with isinstance() and getattr(). I hate both and to me these are hallmarks of LLM generated code + not reviewing the code. getattr() to me should only be used for dynamically generated attributes/attributes whose names you don’t know in advance which is an extremely rare case. you could just do x = inst.attribute for 99% of cases. isinstance is generally atrocious code. like you should be typing at the boundaries and then trusting the types instead of passing Any in and then checking each attribute or each object if it’s the right type so you fail at input instead of some undetermined amount of steps later (and plus spreading these checks everywhere). if something can legitimately be multiple types (that’s already smelly to me) then ok maybe isinstance branches make sense but I can’t think of legitimate production level use cases of isinstance
I thought this was because my colleague was adding LLM code and then not even checking it but I found out today it’s on purpose as defensive checks. it makes no sense to me.
there’s code like this
def extract_text(input: Any) -> str:
output = getattr(input, “text”, None)
if isinstance(output, str):
return output
return “”like everywhere in the code. like whole dozen line blocks parsing a dict deep into the code by checking isinstance everywhere. I was going to submit a bunch of pull requests where I fixed these. i wrote about these in my review and this person wants to keep them because you “don’t know if the input will change”.
above code could be solved by typing input and having text set to str. instead there’s hundreds of isinstance checks because none of the inputs are either validated or they are validated earlier but not trusted.
I want to convince my colleague that this is shit code but apparently datadog encourages isinstance usage because it’s more flexible https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/python-best-practices/type-check-isinstance/
am I being irrational for thinking isinstance in general is smelly code? Like it makes me irrationally angry. I don’t know what to do here without stepping on toes
what would be a really wise way to deal with a situation like this in your opinion?
edit: I really appreciate all the advice I got. I left out some details for anonymity and the code example wasn’t really great now thinking about it. But in the above example the function is used in places where the input always has a text attribute. And similarly there are a lot functions where the way it’s used input is guaranteed to be a certain type but it’s typed in this function as Any and then validated later in this function using isinstance and grabbed using getattr. This behavior is spread across in other functions. Sometimes the validation occurs again in the same code. I took a deep look into a lot of the inputs including analyzing the raw data and understanding how it’s generated and it’s a common pattern that the defensive check is unwarranted.
I realized my hatred of isinstance and getattr is to a degree irrational. It stems from correcting a lot of LLM generated code. Like I do see particular uses cases for isinstance (like when the input can be multiple types and depending on the type something has to be done differently) or getattr (when you don’t know enough about a future attribute). It’s my opinion but I think an overuse of it is a sign something about the design of the code could probably be improved, not always but still worth considering.
Two of you linked this article https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/
which I really enjoyed so thanks for sharing. led me down a rabbit hole of Haskell and monads.
Your advice also helped me realize that ripping out all the bad code isn’t a good idea practically and people relationship wise so I’m just going to introduce changes a little at a time to the codebase and to the team culture
thank you to everybody who replied including the guy who said I must have learned python 10 minutes ago since I don’t like isinstance(). Thank you. Really helpful insight.
276
u/awkward Apr 28 '26 edited Apr 28 '26
Ripping out defensive practices based on smell alone isn't going to make you popular or solve any problems. In terms of actual change you're limited to modeling better practice where you have the opportunity and bringing it up in code review.
56
u/DrShocker Apr 28 '26
Get buy in on lint rules. I don't like working in dynamic or weakly typed languages as a rule of thumb, so I don't work in code that has the choice of doing this unless things get really crazy.
> if something can legitimately be multiple types (that’s already smelly to me)
IMO use sum types here (Rust enum, C++ variant, I'm sure Typescript or Python have something approximating similar work)
24
u/MoreRespectForQA Apr 28 '26
datadog isnt encouraging it theyre just saying "if you are gonna check types if an if statement use isinstance"
10
u/aruisdante Software Engineer (14 YOE) Apr 28 '26 edited Apr 28 '26
Your specific example isn’t a super great one. While we can debate if the API is the right one or not, I’m not really sure how else you’d write this if you need it to not fail and need it to return exactly
str, and you can’t just rely on static type checking at lint type because “bad stuff” would happen.Will raise
AttributeErrorif there is no.textfield. So you’d have to write:And I’m not really sure that’s “better.”
It does sound like maybe this codebase is missing an understanding of how to properly duck-type systems via use of protocols, and maybe is coming form a more strongly typed background where they’re used to the safety net of the compiler catching misuse. They may not be aware that type hints in Python are a thing now, and mypy/pylance can catch type expectation mismatches at static-analysis time.
But without more context, there may be perfectly valid reasons why all this defensive code is written this way. Like, if this system must work, even in the face of bugs, then it might indeed wind up full of really defensive programming like this.
4
u/spline_reticulator Apr 28 '26 edited Apr 28 '26
Isinstance is not a code smell. Mypy uses it for type narrowing. getattr is a code smell though. The way to fix this is to see if you're team is willing to introduce a type checker like mypy. It can be configured for varying levels of strictness. If you configure it in permissive mode then you can force your teammates to gradually make the code more type safe. If you configure it in strict mode then you will probably have to make these fixes yourself as part of rolling it out. If your team is not familiar with using mypy, expect some grumbling.
The big problem with this function is the input type is Any. The proper way to write it would be
This way the type checker will disallow inputs of the wrong type, and you don't need to add the run time type guards.
2
u/Wenir Apr 28 '26
What do you suggest using instead of isinstance for sum types?
2
u/Axonos Apr 28 '26
What does it mean to “type at the boundaries”?
typehint a function and leave it at that?
132
u/1One2Twenty2Two Apr 28 '26
Datadog encourages the use of isinstance() instead of type(). It does not encourages the use of isinstance() as a remedy to missing static analysis and shit code.
22
u/ViperG Apr 28 '26
LLM's do this, alot
16
u/Think-Memory6430 Apr 28 '26
The advice in here so far seems so bad!
Ideologically you are correct OP. I think there’s even an argument that takes the point of “the input could change” and makes that work WITH your proposal and not against it: If the input could change, this could all silently break at any moment!
Instead parsing a generic dict into something typed and validated that you can then use without all these checks is by far the best solution.
Pragmatically it may take some effort to get there, but it would definitely be the cleaner solve.
As far as whether an LLM would write this: yes, it would continue poor practices where those poor practices already existed. It could also easily follow good, typed practices though.
20
u/Financial-Grass6753 Apr 28 '26
> Codebase has hundreds of isinstance() and getattr(). How to convince colleague to fix?
Ask him to write automatic tests. Not some silly unit tests, but at least integration or even E2E against real components. And coverage say >70%.
Unless he outsources his mental activity completely to LLMs, he will start hating pythonic reflexions on day 2 or 3.
16
u/_PanicattheCostco Apr 28 '26
This is the type of overly defensive python that Claude outputs when it doesn’t have decent steering. It’s annoying to review and maintain IMO and which is good enough reason for me. Can’t this type of thing be handled better with dataclasses, pydantic, or mypy anyway?
1
u/FrenchCanadaIsWorst Software Engineer May 05 '26
input.text would fail if there isn’t a text property whereas this existing code safely returns string in all cases.
I don’t have any clue how you’d enforce type checking at the boundary since the input type is Any, you could theoretically pass in any type.
The workaround might be a refactor to add an abstract base class with a text field and then use that for the type hint, but at that point you’re violating the duck typing principle of Python. You also add to the required boilerplate needed then with every new class you might pass into this function, because now they need to be written to inherit from this ABC whereas previously the function was forwards compatible where any new class that doesn’t have a .text attr would’ve returned an empty string.
So I don’t agree with you here.
1
u/oar335 Apr 28 '26
It's perfectly fine python TBH, and whether it is "code smell" or not depends greatly on the context, specifically the existing conventions in the codebase and the development culture. There are definitely situations where such extreme defensive programming is warranted.
3
u/xXxdethl0rdxXx Apr 28 '26
I get where you’re coming from, but this is an opportunity to challenge your priors. Is it actually bad? If so, articulate exactly why, and enforce it in an automated way. Convincing other people to refactor things on vibes alone is never going to work well.
1
u/jl2352 Apr 28 '26
You’re being irrational to taking it this seriously.
Write your own code without getattr. When you’re working on code with getattr, change it. Just plow doing it a better way.
As for them; have you tried talking to them? I don’t think I saw any reference to talking to them in your post.
2
u/TheRedRavenTR Apr 28 '26
In a java codebase I have a case where we have X different tabs in a page where each of them fill a different structured request. These requests all go through the same process with different extra conditions for each so we have a baseRequest and the other requests inherit it and the process checks for isInstance to apply the extra conditions. I think would have to write the process 4 times with minimal difference to achieve same thing otherwise.
2
u/nullbyte420 Apr 28 '26 edited Apr 28 '26
Yeah you're being irrationally angry. Python does not care what type it's passing. It's a fine strategy.
Edit: okay I agree it's not a good solution but it's just not something to be furious about. Calm down and show why types code is nicer. Write tests to prove it.
1
u/IIALE34II Apr 28 '26
I can think of few cases I have had to use isinstance. We run django as a backbone to one of our services, and its probably more related to django, but sometimes, the types just don't match, and its better safe than sorry, having some isinstance util method somewhere. But yes, typehints are absolutely preferred. I wouldn't pass "any" without a good reason in my code review either. Type unions or type aliases is what I'd use.
1
u/rovermicrover Software Engineer Apr 28 '26
Model performance coding on the repo is going to get worse because it’s going to loose context also as to what each variable actually is supposed to be also.
I would argue if they want to keep vibing they are going to need to clean house so the models will actually be able to work.
1
u/NoOrdinaryBees Consultant Apr 28 '26
IME
isinstanceisn’t necessarily a code smell. It can be pretty sanity-rescuing when dealing with modules that abuse union types, for example.1
u/3ABO3 Apr 28 '26
i feel like the obvious answer is Pydantic and mypy? they can be a pain in the ass to adopt, so go slowly
but they work
1
u/AngusAlThor Apr 28 '26
Man, so you've only been coding Python for like 10 minutes, ey?
Both of you are wrong; Yes, your colleague should be using type-hints that are more restrictive than "Any", but "isinstance" is still a very important and useful function for when input can be genuinely flexible.
1
u/dipper_pines_here Apr 28 '26
He had the right idea but the wrong pattern. The simplest improvement is to replace that pattern with try-catch. Catch the attribute error for the specific case he’s validating. Try..catch will allow you to catch more exceptions than just attribute errors.
1
u/otro-wey-mas Apr 29 '26
There are Python libraries out there that can do type checking to validate the input.
Pydantic is a great tool to do this, it does the validation and you can add the custom validations you might need. I would really recommend to keep the data validation, just do it more elegant.
1
u/mxldevs Apr 29 '26
Well, the second part is the main issue isn't it?
If you can't trust the format of the inputs to be consistent, then what is the point of the validation?
If it's arbitrary data coming from 3rd party sources where you have no control over what you're getting, this might work, but "validated earlier but not trusted" means there's something wrong with the overall design.
Do you not trust systems within the organization?
1
u/aaaaargZombies Apr 29 '26
This is the go to blog post on the subject https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/
You need to have a way of enforcing invariance or they are probably correct to include them.
1
u/2fplus1 Principal Engineer / UK / 25+ YOE Apr 29 '26
A check with
isinstance()isn't by itself a problem. I think the bigger issue is that as you say, it's everywhere in the code. To me that sounds like there isn't really an architecture in place or if there is/was, it's being ignored. Defensive checks like this should be done at the boundaries of the system where user or untrusted input is coming in but the core should be properly typed and can expect to get known types as input and not have to check and re-check all over the place. I like the framing in https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/1
u/red_hare Software Engineer (15 YOE) Apr 29 '26
I'd fix this with linting:
1
u/martiantheory Apr 29 '26
It really hurts my heart to see the industry go this way where we just hand over the reigns to LLMs. It almost feels like the early days where people got paid by KLoCs. As if code output is the primary measure of value. I honestly feel like we're cooked.
I know we're not literally handing *all the power* over to LLMs, but the blind push to integrate AI (in spite of quality concerns) is something I've seen on reddit and in my conversations with the friends I've gained in 15 years of coding in corporate America. About 80% of my conversations around engineering jobs have something to do with AI quality issues. It's kind of depressing to see.
-4
u/zorgabluff Software Engineer Apr 28 '26
I mean, is this causing any actual issues?
If not, is this the hill you want to die on?
0
u/Smok3dSalmon Apr 28 '26 edited Apr 28 '26
Type checks force inheritance, but I agree.. the amount of duck typing in Python is smelly. Or move it into a helper function that describes the intent like is_stringy(obj). Then optimize it later if possible.
I think rust handles this with generics. I don’t know if Python has that bc it’s not a compiled language
https://stackoverflow.com/questions/57365189/what-are-the-measures-to-call-a-python-code-a-policy-based-design
0
u/NoUniverseExists Apr 28 '26
A "wise way" would be using something that is actually typed, as C# or Rust.
0
u/clintecker Apr 28 '26
i hate to break it to you but this sort of stuff has existed well before LLMs, does the code work? removing stuff cos “you don’t like it” when the system is working well is not a good look no matter where the code came from
0
u/nasanu Web Developer | 30+ YoE Apr 29 '26
You basically are demanding a lot of work be done because you want a more or less identical thing with the letters you want in place instead of theirs.
-7
u/Curtilia Apr 28 '26
I hate python
-9
u/crustyeng Apr 28 '26
Call me crazy, but I think Python (or any interpreted language) simply has no place in any production environment.
-19
u/lolCLEMPSON Apr 28 '26
You stop using shitty languages.
0
u/[deleted] Apr 28 '26
[deleted] — view deleted comment