frozenset/subclassing/keyword args

Mark E. Fenner Hobbes2176 at yahoo.com
Tue Nov 1 22:06:55 CET 2005


> Without researching it, I would guess that you have to override __new__
> so as not to pass through the myName arg to the otherwise inherited and
> called-with-all-arguments __new__ of the base class. 

<snip>

> Regards,
> Bengt Richter

Bengt,

Thanks as always!  Python's rabbit holes always go a little deeper then
you've currently gone.  My one irritation is that it seems that the error
message could give some indication of where the problem lies.  "bad args to
__new__", "immutable's bypass init", "black voodoo ahead" ... but I know,
efficiency, conciseness, other concerns, etc. etc.  Doesn't mean I can't
gripe about it!  

As you said, there are a number of threads on this.  Consulting those gave a
quick three line solution, shown below.

Regards,
Mark

P.S. Here's what I should have been doing:

******************** start file *********************
#!/usr/bin/env python

from sets import ImmutableSet

class MSet1(ImmutableSet):
    def __init__(self, iterArg, myName="foo"):
        ImmutableSet.__init__(self, iterArg)
        self.name = myName



# works
class MSet2(frozenset):
    def __new__(cls, itrarg, *args, **kwargs):
        return frozenset.__new__(cls, itrarg)

    def __init__(self, iterArg, myName="foo"):
        frozenset.__init__(self, *iterArg)
        self.name = myName

# broken
class MSet3(frozenset):
    def __init__(self, iterArg, myName="foo"):
        frozenset.__init__(self, *iterArg)
        self.name = myName

m1 = MSet1([1,2,3], myName = "donkey")
print m1
print m1.name

m2 = MSet2([1,2,3], myName = "mario")
print m2
print m2.name

m3 = MSet3([1,2,3], myName = "kong")
print m3
print m3.name
******************* end file ****************

************* sample run ******************
MSet1([1, 2, 3])
donkey
MSet2([1, 2, 3])
mario
Traceback (most recent call last):
  File "./setTest.py", line 33, in ?
    m3 = MSet3([1,2,3], myName = "kong")
TypeError: frozenset() does not take keyword arguments
************** end run ***********************




More information about the Python-list mailing list