Skip to content
Advertisement

How to perform input validation for read-only instance attributes?

A very similar question was posted here, but there are no accepted answers, no code examples and I don’t really like the idea of using an external library as suggested by the only one answer provided there.

The following code allows to define read-only instance attributes:

JavaScript

but I would like to validate the user inputs as well. I want to validate if x and y have the right type.

What is the most pythonic/elegant way for doing this? If I provide setters, the attributes are no more read-only.

Is performing the input validation within the constructor the only way to go?

Advertisement

Answer

Here’s an elegant and pythonic way to do it which uses a factory function to create the properties:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement