0

I'm familiar with the C# syntax to, for example, create a list of strings by List<string> MyList.

Is there a similar syntax in python that will cause it to fail if I attempt to add a type that is not in the collection type?

2
  • You would have to create a custom class. Such functionality doesn't exist in Python Commented Oct 5, 2011 at 1:35
  • This is not the Python way. If this is to be used internally in your code, just don't put anything else than strings into the list. If this is to be exposed to the users of a module you're writing, just document it properly. This way the list can contain anything that behaves like a string but isn't necessarily a string. See "duck typing" and EAFP for more info. Commented Oct 5, 2011 at 2:25

2 Answers 2

1

As others have said, Python doesn't have anything like that built in.

If you wanted to make something like that, you would subclass the built-in list() class, and make all the methods that allow inserting or appending elements do a type check. Or, instead of the type check, you could make your custom methods try to coerce the type.

Here is an example implementation of a list that will only hold int() values. It will coerce anything you try to insert or append into it, and raise an appropriate error. I subclassed the built-in list() type, so the code I wrote is just the exceptions; anything you don't see here will work exactly as the base list() type. I just needed to hook a few methods. I also gave it a custom .__init__() method that accepts a list or other sequence and initializes the object.

This is an incomplete implementation; for example, it doesn't override the .insert() method. But I think it shows you the basic idea, and if you really wanted an IntList() class you could use this as a base.

class IntList(list):
    def __init__(self, seq=None):
        if seq is not None:
            try:
                for x in seq:
                    self.append(int(x))
            except ValueError:
                raise ValueError, "can only use int values to init IntList"
    def __setitem__(self, i, x):
        try:
            list.__setitem__(self, i, int(x))
        except ValueError:
            raise ValueError, "can only set int values into IntList"
    def append(self, x):
        try:
            list.append(self, int(x))
        except ValueError:
            raise ValueError, "can only append int values to IntList"


lst = [0, 1, 't']

try:
    o = IntList(lst) # raises exception
except ValueError:
    print("lst has a 't' in it")

o = IntList(range(3))  # works

try:
    o[1] = 't'
except ValueError:
    print("cannot set to 't'")

o[1] = 2  # works

o.append(4)  # works
o.append('t') # raises error

The above prints:

lst has a 't' in it
cannot set to 't'
Traceback (most recent call last):
  File "t.py", line 38, in <module>
    o.append('t') # raises error
  File "t.py", line 18, in append
    raise ValueError, "can only append int values to IntList"
ValueError: can only append int values to IntList

There is a common Python idiom of having a default argument set to None for list arguments in .__init__() functions. This is because the default value list is only evaluated once, at compile time, and saving a reference to this list would mean that every instance of the class shared the same instance. In this case, since we have a for loop iterating over the loop, building our own copy, I don't actually need to do this idiom; but I wanted to give an example of the idiom for the benefit of newbies reading this.

Sign up to request clarification or add additional context in comments.

Comments

1

No. You will need to create a custom class that implements the __*item__() methods appropriately.

2 Comments

I'm still a python learner, do you have any examples of using the __*item__() methods in action? (specifically using python 2.5 since I'm working on google app engine)
Try clicking on the word "methods" in the above answer. It is a link to a Python documentation page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.