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?
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?
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.
No. You will need to create a custom class that implements the __*item__() methods appropriately.