Uncommon Uses of Python in Commonly Used Libraries (2022)

https://news.ycombinator.com/rss Hits: 7
Summary

To learn how to build more maintainable and usable Python libraries, I’ve been reading some of the most widely used Python packages. Along the way, I learned some things about Python that are off the beaten path. Here are a few things I didn’t know before. Using super() in base classes Python’s super() lets us inherit base classes (aka super or parent classes) without having to explicitly refer to the base class. It’s usually used in the __init__ method. While this might be simply a nice-to-have in single inheritance, multiple inheritance is almost impossible without super(). However, one interesting use of super() is calling it in the base class. I find noticed this in requests’ BaseAdapter. class BaseAdapter: """The Base Transport Adapter""" def __init__(self): super().__init__() def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): Given that the base class doesn’t inherit from anything, why call super() in it? After a bit of digging, here’s what I learned: Using super() in the base class allows for cooperative multiple inheritance. Without it, the __init__ calls of parent classes—after a non-supered class—are skipped. Here’s an example with a base class (BaseEstimator) and mixin (ServingMixin), both of which will be inherited by our DecisionTree class. First, we have a BaseEstimator that doesn’t call super() in its __init__ method. It has a basic __repr__ method to print attributes. class BaseEstimator: def __init__(self, name, **kwargs): self.name = name def __repr__(self): return f', '.join(f'{k}: {v}' for k, v in vars(self).items()) Next, we inherit BaseEstimator via the DecisionTree subclass. Everything works fine—printing the DecisionTree instance shows the attributes of BaseEstimator and DecisionTree. class DecisionTree(BaseEstimator): def __init__(self, depth, **kwargs): super().__init__(**kwargs) self.depth = depth dt = DecisionTree(name='DT', depth=1) print(dt) > name: DT, depth: 1 Now, let’s also inherit ServingMixi...

First seen: 2025-07-07 05:26

Last seen: 2025-07-07 11:26