3 ms·
Personally I'm not in favor of enforcing such strict conventions, especially in a dynamic language like Python. Also isn't this pattern he repeats throughout:
by mrshoe 15y ago
Personally I'm not in favor of enforcing such strict conventions, especially in a dynamic language like Python. Also isn't this pattern he repeats throughout:
class Shape:
def __init__(self, **kwds):
self.shapename = kwds.pop('shapename')
super().__init__(**kwds)
Better written like this?
class Shape:
def __init__(self, shapename=None, **kwds):
self.shapename = shapename
super().__init__(**kwds)
It seems like there are some things about Python's which the author doesn't like, and he solves them by adding a lot of boiler plate to each of his classes. It's probably a better idea to just embrace the Python way or use a different language.
- teh 15y agoThe issue with your second version is In [1]: def init(shapename=None, **kwargs): ...: pass ...: In [2]: init(shapename='circle', **{'shapename': 'circle'}) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/teh/Desktop/<ipython console> in <module>() TypeError: init() got multiple values for keyword argument 'shapename'
- Peristarkawan 15y agoThat's entirely the caller's fault, not the function's. Compare: >>> def init(**kwargs): ... pass ... >>> init(shapename='circle', **{'shapename': 'circle'}) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: init() got multiple values for keyword argument 'shapename'
- narm60 15y agoThese two aren't equivalent, the first example requires the shapename keyword arg, raising a KeyError when it wasn't specified
- Peristarkawan 15y agoThat's true. The second one might be better written as: def __init__(self, shapename, **kwds): Or, in Python 3: def __init__(self, *, shapename, **kwds): (making shapename a required keyword-only argument)
- reinhardt 15y agodef __init__(self, shapename, **kwds): is not better written; it allows shapename to be passed positionally which makes cooperative inheritance fragile.
- Peristarkawan 15y agoThe version that I was rewriting: def __init__(self, shapename=None, **kwds): also allows that.
- mixmastamyk 15y agoHaha, the author is one of the main contributors to python, not some high-schooler. kwds.pop('shapename', None) Will get you what you're looking for.