17 ms·
Python at Scale: Strict Modules
- pmiller2 6y ago(2019) Previous discussion: https://news.ycombinator.com/item?id=21284669 https://news.ycombinator.com/item?id=21284669
- cutler 6y agoWhy not just use Clojure?
- cat199 6y agofrom tfa: "One reasonable take might be that we’re stretching Python beyond what it was intended for. It works great for smaller teams on smaller codebases that can maintain good discipline around how to use it, and we should switch to a less dynamic language. But we’re past the point of codebase size where a rewrite is even feasible. " YMMV.
- Guthur 6y agoI've been doing this for long enough to know that if you think static typing will save us from the complexity of large organically grown code bases you'll be sorely mistaken. The code and system design will reflect you culture per Conway's. If you value fast delivery it'll be full of dirty hacks throughout, piling one on top of each other. If you have single tight nit team it'll ram a million and one concerns into the same system, and so on. Languages will not save us from ourselves, ever.
- sateesh 6y agoI agree static typing is no silver bullet.But when there is a choice between looking at python code written some time ago and wondering (and at times speculating) what type the function args are v/s inferring from function args (say in Go) is a smoother experience, especially when debugging a thorny heisenbug causing an outage.
- Guthur 6y agoDon't worry golang will have it's day of horror story code bases where developers made all sorts of wacky decisions around pointer passing and badly specified interfaces within a code bases 100kloc too large.
- redis_mlc 6y agoFYI: Perl5 has always had moderately strong static typing and runtime warnings, as well as forward references. I always wince when people try to tell me that python is "better" or "more modern." To enable in Perl: use strict; use diagnostics;
- mhh__ 6y agoI think this is true however there is a tendency to think that not using Python can only mean using C++, Something on the JVM, etc. C++ is an awful language, you can do better (albeit it's potentially not for the faint of heart) Static Typing is important, but the thing with Python is really the lack of a compiler - compilers (ignoring efficiency) catch bugs now rather than half way through a job (Obviously Linters do exist but a sufficiently advanced Linter is not only repeating work a compiler would've done, but also probably requires some kind of help e.g. annotation) An example of something that demonstrates Static Typing working and not working at the same time: Compare the code of GCC and LLVM, they're both in C++ (now) but one is hugely better structured and easier to read - GCC grew organically which is part of the problem, but LLVM was specifically designed around a certain architecture (And still grew quickly). To paraphrase Batman, "It's not what type-system I use underneath, but what I do that defines me" definitely applies but drawing equivalence between all code regardless of language isn't right either - the language you use affects the way you code and how you structure your programs.
- dragonwriter 6y ago> Static Typing is important, but the thing with Python is really the lack of a compiler - compilers (ignoring efficiency) catch bugs now rather than half way through a job Nope, that's static type checkers (which are often part of compilers), not compilers as a separate thing from static type checking. In fact, Python has a compiler run in the course of normal execution. And Python also has static type checkers available (and good editor integrations for them), they are just separate from the compiler. > Obviously Linters do exist but a sufficiently advanced Linter is not only repeating work a compiler would've done, but also probably requires some kind of help e.g. annotation) Yes, static type checkers whether incorporated in a compiler or separately tend to need type annotations to do their best work, especially if the type system isn't specifically crafted to maximize inferrability (Haskell can get away with fewer annotations than Java, often.)
- oblio 6y agoGiving up and not using superior tools won't help us, either.
- lmm 6y agoThat's like saying a workout plan can't keep you in shape because you need discipline to stay in shape. Static typing is the only way I've found to save you from yourself; it's how you can set guardrails that make it easier to do the right thing than the wrong thing. If not static typing then what?
- pjmlp 6y agoI learned during the first .com wave while using our own in-house version of ActiveAOL inspired server, and friends doing Zope projects, not to take shortcuts with dynamic languages at scale. Static typing does solve some issues, provides tooling opportunities, and easier ways to generate native code when that performance gets called into action and like here the application is behind any hope of getting rewritten. In fact, pretty much so, that all dynamic languages that got widespread adoption are now trying to fit some kind of static typing support into their infrastructure.
- luord 6y agoIndeed. In fact, a strong contender for the absolute worst codebase I've worked on was in Go. No type system is going to save you if you if you don't follow pretty much any good practice. Conversely, well modeled systems can be coded in any language, as long as good practices and good communication are continuously enforced. There are even studies on this and, so far, there's no strong correlation between type system (or paradigm, for that matter) and number of bugs in a codebase. In fact, one recent study on the matter ended up turning into a flamewar between two different groups of scientists, the ones who first published the study and the ones trying to replicate and double check the data... As discussions on type systems and paradigms are won't to do. Evidently not even academia is safe. I wish there actually were empirical evidence to support one's preference in that area, if only to get rid of those flamewars that have been going on for decades. Alas, until that happens, what language one prefers mostly remains opinion or personal experience.
- strokirk 6y agoCan you send a link to the study? Sounds interesting!
- luord 6y agoMy favorite summary of the whole thing is here: https://www.hillelwayne.com/post/this-is-how-science-happens/ https://www.hillelwayne.com/post/this-is-how-science-happens... It was shared here a while ago (https://news.ycombinator.com/item?id=22531453 https://news.ycombinator.com/item?id=22531453), if you also want to read the HN discussion about it.
- lmm 6y ago> In fact, a strong contender for the absolute worst codebase I've worked on was in Go. So the most notoriously limited typesystem of the century, the one that ignored decades of progress, lead to a bad codebase? And you see this as an argument against type systems?
- luord 6y agoI don't think I was making any arguments. Furthermore, if there's a takeaway from my comment, is that I don't think there are arguments to be said in that particular discussion, only opinions supported by one's specific experience. There's certainly a dearth of solid empirical evidence one way or the other. I was also agreeing with GP's saying that "static typing won't save us". There are many things to say about Go's type system, but it is definitely more static than Python's, which I've also worked with.
- avador 6y agoLook, here we have the humble “Just”, sitting low in the wordy shrubs, almost hidden from view, pecking at its surroundings with confidence. Its natural habitat rife with nutrition, the Just pecks in any direction it likes, and, with ease reminiscent of more rare species, like the Merely, or the Simply, fills itself up for blind and rampant reproduction across all the fields of human thought.
- alexpetralia 6y agoSo funny. Love this. I imagined David Attenborough's voice.
- coldtea 6y agoThey have a problem in their Python codebase, and someone says, "why not just use Clojure". Now they have 50 problems. 1) Porting hundreds of thousands of lines of code 2) New infrastructure (for building, testing) 3) Training programmers in Clojure and waiting for them to get good 4) New Clojure dev hires 4) New bugs due to porting 5) Packages they rely on not being available 6) ... I mean, do people even stop to consider things when making such suggestions?
- taeric 6y agoIt's odd. The crux of this post seems to be about not allowing new commiters to do many of the tricks that got the code to where it is. Which is fair, but also muddies a point. That being that many will just point out how they shouldn't have done all of those tricks. Many actually sound like a straw man. Laughably so. But they got them to where they are.
- rurp 6y agoThis was a great article that I learned a lot from. One part stood out a bit though. def myview(request): SomeClass.id = request.GET.get("id") Is this pattern common in Python projects? A coworker and I were discussing solutions to a tricky problem the other day and one solution that involved a step like this was immediately dismissed as likely to cause a huge mess. We're far from world class Python developers and would definitely struggle with the other issues outlined in the post, but this one seems pretty clear.
- whb07 6y agoThe problem with this is something most Pythonistas don’t think about, the return type of the function. Officially it’s either a None or Int. But most people would just say Int. Will cause problems obv when not properly handled.
- hannofcart 6y agoPython type annotations, especially the 'Optional' type annotation in conjunction with a good typechecker like mypy alleviates this problem.
- whb07 6y agoAgreed, there is a perverse attitude where people jump into Python for the “it just works!” mentality, and hate the idea of type annotations.
- zo1 6y agoI'm confused, the function doesn't return anything so why would it be an int return type? It should be "None" because it's a void function.
- whb07 6y agoOof well let’s just assume it did, it’s a view about the specific user-ID so in theory it would return that. I misread and then I’ll blame my mind for thinking implicit return as last line ;)
- ilaksh 6y agoThey should have looked into Nim.
- coldtea 6y agoYes, they should have changed their hundreds of thousands of lines of code for a new, less popular, less mature, less supported, hugely smaller ecosystem and libs, language, to solve one specific issue they have... /s
- ashish01 6y agoHow can one learn about advanced python concepts like this - slots, meta programming etc. Is there a good book for this?
- sedeki 6y ago"Fluent Python" qualifies, iirc.
- mattficke 6y agoEffective Python is one of my favorite intermediate-level books on the subject https://effectivepython.com/ https://effectivepython.com/
- pjmlp 6y agoThe Python manuals actually, or if you want to dive into the ideas that Python copies from, Lisp books like "The Art of MetaObject Protocol".
- japhyr 6y agoSerious Python is a short, quick overview of some higher-level concepts I wasn't aware of before. I'm working through High Performance Python at the moment, and it's a much more in-depth treatment of similar concepts. https://nostarch.com/seriouspython https://nostarch.com/seriouspython https://www.amazon.com/High-Performance-Python-Performant-Programming-dp-1492055026/dp/1492055026/ https://www.amazon.com/High-Performance-Python-Performant-Pr...
- Jiocus 6y ago“the order of imports is [..] an emergent property of the imports present in all modules in the entire system (and can also vary based on the entry point to the system).” I think this sounds beautiful.
- p5a0u9l 6y agoI couldn’t tell, is __strict__ something they’ve implemented in house, or exists in CPython? I can’t find any references to it outside that article.
- eshyong 6y agoFrom the last paragraph: > Strict modules are still experimental. We have a working prototype and are in the early stages of rolling it out in production. Sounds like it's in-house to me.
- coldtea 6y ago"Many thanks to Dino Viehland and Shiyu Wang, who implemented strict modules and contributed to this post."
- codethief 6y agoYeah, that was my impression, as well. Does anyone know whether they've released the code of their prototype somewhere?
- aitchnyu 6y agoIts a fork of Cpython interpreter right?
- matesz 6y ago> 90. Consider Static Analysis via typing to Obviate Bugs Personally I wouldn't recommend using typings (we've tried around 1 year ago for multiple greenfield services ~5k LOC each): - you will be better off investing into proper testing (I mean here code coverage), refactoring and onboarding documentatio/handholding sessions with devs who are on top of the codebase - in practice annotations make code LESS readible, not more (unless variable names and general code structure and conventions are bad) - remember most Python devs have little experience with staticly typed langauges, so in practice your team will be skipping annotations - e.g using Dict[str, Any], which defeats the whole purpose of annotations; actually seasoned C++ devs will be skipping it once they will see they can get away with it Typings are still in 0.x version and are constantly changing - do it for fun or to put typings on your CV, but don't expect it's going to help with readibility, bug prevention, documentation. These are solved with proper structure, conventions, testing and developer prep (readme + pairing). If you believe bigger projects need annotations tell me why Sentry didn't go with them yet?
- Barrin92 6y agoanother solution yet is going back to one of the fundamental principles of message based OO, leaving interpretation of what objects receive and how to handle them to the object. I've always disliked the idea of using static code-evaluation tools on dynamic object oriented languages, it kind of defeats the point, which is runtime dynamism.
- lmm 6y agoThat's not the solution, it's the problem. A large system is impossible to understand when state could be anywhere and any part could be coupled to any other part. I think you're partly right, but ultimately runtime dynamism has failed; even in Python, the costs of being truly dynamic are higher than the benefits.
- Barrin92 6y agothe intention of that proposed solution is radical decoupling though. Think of objects being used analog to network servers. The internet doesn't go down because someone's server changes (the BEAM VM probably comes closest as far as languages are concerned). Objects communicate messages and status and when something crashes it's up to the object to do something, often restart, but either way it's a matter of interpretation. It's the static typing that couples because it introduces global behaviour through its types, which impose meaning from the top. In a truly dynamic system, nobody needs to understand the entire system. I admit it's a fairly theoritcal point because I don't think many people even embrace this paradigm any more, and ironically if they do it's in functional languages. But to say it's failed I think is not right, because nowadays people write dynamic languages basically like they'd write Java, they don't embrace the dynamic aspects.
- divtiwari 6y agoThey should rewrite it in Rust!! /s
- krab 6y agoI worked on a codebase in Django that started in > 5s (after removing all side effects and moving optional stuff to be lazily loaded). Incremental reload would be useful, for sure. Even with times in the range of multiple seconds, the reload slows you down noticeably. Compared to Java, we had slower startup times with Java, but then the hot reload worked very well, directly from IDE.
- carapace 6y agoFootguns upon footguns and armored boots made out of footguns.
- cosmic_quanta 6y agoTo be fair, from the article: > But we’re past the point of codebase size where a rewrite is even feasible. So realistically, what else can they do?
- carapace 6y agoThey've built themselves a special kind of hell. I call this sort of thing Winchester Mystery House development. It's amazing what you can get away with when you're sitting in a fire-hydrant of money. Entropy, gradients, etc., like radiotrophic fungi in a cracked reactor this codebase has burgeoned and now they have a tiger by the tail, a mutant three-headed tiger with laser eyes. Anyway... Imagining myself coming in as CTO or whatever, with the mandate to "fix" the situation (is Instagram in any sort of trouble? I don't follow such things. The point is, maybe it isn't broken by the metrics that IG cares about.) ...this is what I'd do. Since I don't have a lot of data on the details of IG's code (and I can't bring myself to reread that horror story this early in the morning) I can only speak in generalities. The most important thing would be that there's a real mandate to "get 'er done", with that hypothetical postulated, I'd issue some top-level directives: #1) Reduce LoC by 10% per month. #2) 1/5 of all coders are on refactoring duty, not features. #3) Start counting the beans. Track the cost of existing features to be able to predict the cost of proposed features. Not being a particularly original thinker, I'd lean heavily on prior art cribbed from the movie industry. To wit: "Hollywood Secrets of Project Management Success" by James Persse https://www.microsoftpressstore.com/store/hollywood-secrets-of-project-management-success-9780735625693 https://www.microsoftpressstore.com/store/hollywood-secrets-... If you reduce LoC, prioritize refactoring, and track your actual costs transparently, I think that would have a chance of righting IG's software boat.
- strokirk 6y agoWhat would your replacement language of choice be? Personally I'd balk at forcing all my developers to learn the new, untested language. The grass always seems greener before jumping over the fence.
- memco 6y ago> log_to_network(f"{func.__name__} called!") I'm seeing a lot of examples of logs using f-strings, but I was taught that you should use % string syntax because it would more optimally handle the string when logging is filtered, disabled, etc. Is my understanding faulty, outdated or correct and unused by others?
- karlicoss 6y agoI guess, by %-syntax, you mean templace strings, something like logging.info('logging object %s', obj)? (as opposed to the 'old' printf-style formatting with % operator) This is a fair concern, but in my personal experience, that was never an issue in Python. Sometimes I had similar problems in c++ code, but then typically if you choose c++, it's probably for the very reason you expect to squeeze every last bit of performance. Another potential benefit of pattern strings is that they allow for more defensive behaviour - e.g. imagine __str__ method for obj throws the extension, then f'logging object {obj}' will crash immediately. logging.info('object %s', obj) can catch the exception from __str__, log it, and continue - or imagine a typo in the logging pattern, something like logging.info('objects %s %s', obj1). Depending on the logger configuration, it might just log the error (e.g. 'missing value') and carry on without crashing. Such defensive behaviour may or may not be desirable, of course. In my experience, such errors just never happen (especially the latter, if you use f-strings and mypy, most of these can be statically checked). But YMMV