[Python-Dev] Subtyping mutable and immutable built-in types

Edward C. Jones edcjones at erols.com
Thu Apr 29 00:09:41 EDT 2004


#! /usr/bin/env python

# According to
# http://www.cafepy.com/articles/python_attributes_and_methods/ch03s02.html
# the correct ways to subtype mutable and immutable built-in types are

# Mutable
class MyList(list):
    def __init__(self, itr): 
        list.__init__(self, [int(x) for x in itr])

# Immutable
class MyTuple(tuple):
    def __new__(typ, itr): 
        return tuple.__new__(typ, [int(x) for x in itr]) 

# This doesn't work.
class MyTuple(tuple):
    def __init__(self, itr): 
        tuple.__init__(self, [int(x) for x in itr])

# A variant is
class MyList(list):
    def __init__(self, *args): 
        list.__init__(self, args)

class MyTuple(tuple):
    def __new__(typ, *args): 
        return tuple.__new__(typ, args) 

# This doesn't work.
class MyTuple2(tuple):
    def __init__(self, *args):
        tuple.__init__(self, args)

print MyList(1, 2)
print MyTuple(1, 2)
print MyTuple2(1, 2)

# This warty stuff needs documenting.





More information about the Python-Dev mailing list