Inheriting frozenset gives bug if i overwrite __repr__ method

  • Thread starter srinivasan srinivas
  • Start date
S

srinivasan srinivas

Hi,
I am getting an error while executing the following snippet. If i comment out method __repr__ , it works fine.

class fs(frozenset):
    def __new__(cls, *data):
        data = sorted(data)
        self = frozenset.__new__(cls, data)
        self.__data = data
        return self

    def __repr__(self):
        return "%s(%r)" % (self.__class__.__name__, self.__data)

a1 = fs(1,2,3)
a2 = fs(3,4,5)
print a1.difference(a2)

Error:
    return "%s(%r)" % (self.__class__.__name__, self.__data)
AttributeError: 'fs' object has no attribute '_fs__data'

Please help me in fixing this.

Thanks,
Srini



Add more friends to your messenger and enjoy! Go to http://messenger.yahoo.com/invite/
 
M

Mark Dickinson

a1 = fs(1,2,3)
a2 = fs(3,4,5)
print a1.difference(a2)

Error:
    return "%s(%r)" % (self.__class__.__name__, self.__data)
AttributeError: 'fs' object has no attribute '_fs__data'

I guess you need to implement the difference method in your
subclass.

It's a little odd that an operation on subclasses of frozenset returns
an instance of the subclass, rather than simply a frozenset. Most
other
Python types don't work that way. Compare and contrast:

Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
class myint(int): pass ....
a = myint(3)
b = myint(5)
c = a+b
c 8
type(c)
class fs(frozenset): pass ....
a = fs([1, 2, 3])
b = fs([3, 4, 5])
c = a - b
c fs([1, 2])
type(c)

Mark
 
G

Gabriel Genellina

I guess you need to implement the difference method in your
subclass.

It's a little odd that an operation on subclasses of frozenset returns
an instance of the subclass, rather than simply a frozenset. Most
other
Python types don't work that way. Compare and contrast:

Yep; looks like a bug in the set/frozenset implementation. Usually builtin
types don't return subclasses because they don't know how the constructor
should be called - it is indeed the case here, as the OP has changed
frozenset.__new__ signature. Even if fs.__new__ were called its arguments
would be wrong.
The bug is not that the subclass constructor is skipped, but that
a1.difference(a2) returns a subclass instead of a frozenset instance.
(set and frozenset are unrelated types but share a lot of their
implementation by using generic algorithms, and it's the generic part the
culprit here)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top