Question

I'm reading the python tutorial. The 3rd paragraph confuses me a bit.

"Clients should use data attributes with care — clients may mess up invariants maintained by the methods by stamping on their data attributes."

What exactly do they mean by invariants? Do they mean data attributes that certain methods rely on? (e.g a method that returns a certain data member; i.e. a getter method)

Was it helpful?

Solution

I believe what they want to say there is that you should be careful when accessing/mutating an object’s properties. (Note that I call them “properties”, not “data attributes”)

This is because an object may put something in a property that might be necessary to maintain an object’s state, i.e. an invariant which you would normally not be given means means to mess with.

But unlike other programming languages, Python does not have any protection for object members. There are no private instance variables or methods, so anyone can change an object in the way they want to, possibly completely destroying its functionality.

So the tutorial suggests you to avoid storing important things in properties—but to be honest, there is not really a much better way, and if someone would want to mess with it, they just could. For example you can swap out whole methods at run time, replacing them with a completely different logic.

So trying to protect yourself too much is not really worth it. Instead, I would suggest you to just document everything in a clear way. E.g. point out which properties are free to touch by users, and which are for internal use only.


† There are some means and conventions, e.g. one leading underscore for internal/protected members, and two leading underscores for private members, but those will not technically prevent you from accessing it, so it’s not a protection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top