In Python luckily most of the times you don’t have to write getters and setters to get access to class properties. That said sometimes you’ll have to remember that a certain property is a list or whatnot and a property would save you there by abstracting the type and providing a setter to add something to such list for example rather than exposing the list directly.
Where do you draw the line between exposing the type directly or wrapping its access in a property? What’s the general “pythonic” advice?
2
I’ve been having an internal struggle with “Pythonic” code vs. “well architected” code (well, in an academic sense anyway) for a little while. The more time I spend writing Python code in a professional capacity (and dabbling in OSS), the more I realize that to be “Pythonic” is sometimes throwing away everything that you’ve ever learned about “correct” OOP.
Nothing in Python is truly private. As such, there is no reason to have getters and setters. Yes, you can use decorators (@property
, etc), but I’ve found little use for them other than to bloat my code (and they’re very rarely used in any code that I’ve looked through).
As for type checking, I rely on the user of the code to be smart enough to know what they’re doing. If they use an incorrect type, somewhere down the line they’ll be presented with a runtime error that should be easy enough to debug with pdb (or obvious with the error message). Again, code bloat.
Having said that, if there’s something that the client code should be made aware of at runtime (data-driven content, etc), I’ll use assert
, which can be disabled in a non-debug environment with Python’s -O flag.
The “best” Python code can be easily grokked. The less code you write (or the more you delete), the easier your code is to understand. As a shameless plug for a library I wrote, I implemented an OAuth 2.0 client that works across all server side flows and supports multiple providers out of the box in 66 LOC. Compared against one of the first revisions at ~450 LOC, that’s pretty damn easy to understand 😉
After all.. We’re all consenting adults here.
Avoid exposing class members to the outside world. Use getters/setters instead.
The type of the actual member is unknown outside the class, and you can have several setters that set the same member. Each setter can receive different parameters and make the convertion.
I don’t know Phyton but I can give you an example in pseudocode:
public class MyClass {
private String a;
private List<String> l = new ArrayList<String>();
public void setA(String newValue){
this.a = newValue;
}
public void setA(int newValue){
this.a = ""+newValue; // convert to string
}
public void addL(String newValue){
l.add(newValue);
}
}
You then can do this with an instance of that class:
object.setA(1);
object.setA("xx");
object.addL("yy");