Re:Wield Python's super() like a Jedi
by mrshoe on Thursday May 26, 2011 @01:59PM
(#2588752)
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:
Better written like this?
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.
[ Parent
| on HN ]
These two aren't equivalent, the first example requires the shapename keyword arg, raising a KeyError when it wasn't specified
Re:Wield Python's super() like a Jedi
by Peristarkawan on Thursday May 26, 2011 @04:49PM
(#2589389)
That'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) def __init__(self, shapename, **kwds):
is not better written; it allows shapename to be passed positionally which makes cooperative inheritance fragile.
Re:Wield Python's super() like a Jedi
by Peristarkawan on Thursday May 26, 2011 @06:46PM
(#2589704)
The version that I was rewriting:
def __init__(self, shapename=None, **kwds):
also allows that.
Re:Wield Python's super() like a Jedi
by mixmastamyk on Thursday May 26, 2011 @07:35PM
(#2589849)
Haha, 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.The 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'
Re:Wield Python's super() like a Jedi
by Peristarkawan on Thursday May 26, 2011 @03:04PM
(#2589012)
That'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'