4 ms·
This would've been very convenient for lazy loading in a recent python project. I ended up making the husk turn into a transparent wrapper for the loaded object
by yccs27 4y ago
This would've been very convenient for lazy loading in a recent python project. I ended up making the husk turn into a transparent wrapper for the loaded object, unfortunately adding a layer of indirection to every subsequent call. Does anyone here know a better way to do lazy loading objects in python?
- masklinn 4y agoIf all the types are the same shape (at the C level) you can swap the class and all attributes of the husk.
- BiteCode_dev 4y agoUse ChainMap in __dict__
- yccs27 4y agoThat works? Wow, I need to try this.
- BiteCode_dev 4y agoI got carried away: you can use ChainMap, but the __getitem__ is not going to get called: https://bugs.python.org/issue1475692 https://bugs.python.org/issue1475692 So your only valid solution is to use __getattr__, which is guaranteed to work. But either you load all missing value on first access, and you can only lazy load once, or you pay the price of a method call for attribute access every single time. And in all cases, you won't have type hint doing the ork for you. An hybrid strategy would be to always use __dict__ pointing to an empty dict you lazy load later, and @property for attribute that are only for the local object. Then you will pay the price of the of the method calls only for non lazy attributes. Depending of your work load and data shape, one solution will be much better than the other, but nothing as elegant as the ChainMap.