How do I restrict a class member variable to be a specific type in Python?
Longer version:
I have a class that has several member variables which are set externally to the class. Due to the way they're used, they must be of specific types, either int or list.
If this was C++, I would simply make them private and do type-checking in the 'set' function. Given that that isn't possible, is there any way to restrict the type of the variables so that an error/exception occurs at runtime if they're assigned a value of incorrect type? Or do I need to check their type within every function that uses them?
Best Answer
You can use a property like the other answers put it - so, if you want to constrain a single attribute, say "bar", and constrain it to an integer, you could write code like this:
And this works:
(There is also a new way of writing properties, using the "property" built-in as a decorator to the getter method - but I prefer the old way, like I put it above).
Of course, if you have lots of attributes on your classes, and want to protect all of them in this way, it starts to get verbose. Nothing to worry about - Python's introspection abilities allow one to create a class decorator that could automate this with a minimum of lines.
And you just use
auto_attr_check
as a class decorator, and declar the attributes you want in the class body to be equal to the types the attributes need to constrain too: