In the below code, if the @classmethod
annotation is present, the inner def new()
is allowed to stand in for the target's __new__()
-- but the class is passed twice. If @classmethod
is removed then we get an error like "". What is @classmethod
doing here and is there a way to do without it? (My motivation is clarity: code I don't understand seems like an accident waiting to happen.)
"""Namedtuple annotation.
Creates a namedtuple out of a class, based on the signature of that class's
__init__ function. Defaults are respected. After namedtuple's initializer is
run, the original __init__ is run as well, allowing one to assign synthetic
parameters and internal book-keeping variables.
The class must not have varargs or keyword args.
"""
import collections
import inspect
def namedtuple(cls):
argspec = inspect.getargspec(cls.__init__)
assert argspec.varargs is None
assert argspec.keywords is None
non_self_args = argspec.args[1:]
# Now we can create the new class definition, based on a namedtuple.
bases = (collections.namedtuple(cls.__name__, non_self_args), cls)
namespace = {'__doc__': cls.__doc__}
newcls = type(cls.__name__, bases, namespace)
# Here we set up the new class's __new__, which hands off to namedtuple's
# after setting defaults.
@classmethod
def new(*args, **kwargs):
kls, _kls_again = args[:2] # The class is passed twice...?
# Resolve default assignments with this utility from inspect.
values = inspect.getcallargs(cls.__init__, None, *args[2:], **kwargs)
values = [values[_] for _ in non_self_args]
obj = super(newcls, kls).__new__(kls, *values)
cls.__init__(obj, *values) # Allow initialization to occur
return obj
# The @classmethod annotation is necessary because otherwise we get an
# error like "unbound method new takes a class instance".
newcls.__new__ = new
return newcls