Keyword Arguments in __init__ in Classes Derived From Basic

680 views
Skip to first unread message

Sergiu Ivanov

unread,
Jun 6, 2012, 8:18:57 AM6/6/12
to sy...@googlegroups.com
Hello,

Consider the following code:

class MyClass(Basic):
def __init__(self, argument):
print argument

I can create an instance of MyClass in this way:

MyClass("something")

However, I cannot do

MyClass(argument="something")

because of

TypeError: __new__() got an unexpected keyword argument 'argument'

I don't really know much about the intricacies of Python inheritance,
but I can see that Basic.__new__ does indeed not accept any keyword
arguments and I think that may be the origin of my problem.

When I don't subclass Basic, both ways work nicely.

Now, I can achieve what I want by doing

class MyClass(Basic):
def __new__(cls, argument):
print argument
return Basic.__new__(cls)

I *think* this doesn't break anything, but could anyone confirm it?

Also, is there a serious reason to not have Basic accept keyword
arguments? That's likely a noobistic question, so I beg your patience
to bear with me :-)

Sergiu

Tom Bachmann

unread,
Jun 6, 2012, 8:25:21 AM6/6/12
to sy...@googlegroups.com
Hi,

I *think* the reason why basic does not accept keyword arguments is that
all arguments are stored in the tuple self.args, and when providing them
by keyword they have no canonical order any more.

I think the best way to go is to do

class MyClass(Basic):
def __new__(cls, arg1="foo", arg2="bar")
return Basic.__new__(cls, arg1, arg2)

i.e. to manually provide a canonical argument order.

I don't think this should break anything - plenty of sympy objects
provide their own __new__ (all relying on Basic.__new__ eventually, as
far as I know).

Tom

Sergiu Ivanov

unread,
Jun 6, 2012, 8:34:29 AM6/6/12
to sy...@googlegroups.com
On Wed, Jun 6, 2012 at 3:25 PM, Tom Bachmann <e_m...@web.de> wrote:
> Hi,
>
> I *think* the reason why basic does not accept keyword arguments is that all
> arguments are stored in the tuple self.args, and when providing them by
> keyword they have no canonical order any more.

Oh, that makes sense.

> I think the best way to go is to do
>
> class MyClass(Basic):
>    def __new__(cls, arg1="foo", arg2="bar")
>        return Basic.__new__(cls, arg1, arg2)
>
> i.e. to manually provide a canonical argument order.

Aha, great. I was feeling uneasy about not supplying any arguments to
Basic's __new__.

> I don't think this should break anything - plenty of sympy objects provide
> their own __new__ (all relying on Basic.__new__ eventually, as far as I
> know).

Great!

Thank you for the explanation!

Sergiu
Reply all
Reply to author
Forward
0 new messages