[Tutor] Quick Pythonic Style Tips
steve at pearwood.info
Sun Jul 23 21:09:37 EDT 2017
On Sun, Jul 23, 2017 at 07:02:09PM +0400, Abdur-Rahmaan Janhangeer wrote:
> assert(... is liked by some strongly typed programmers
Not just strongly-typed programmers:
> data encapsulation might be depressing to some migrating coders
"Data encapsulation" does not mean "data hiding". Python has excellent
- packages encapsulate modules together;
- modules encapsulate classes, functions and variables together;
- classes encapsulate object state and behaviour together.
Compared to languages like C++ and Java, Python's data HIDING is weak.
Python has no private, public, protected, etc.
But even in the strictest languages like C++ and Java, there is usually
some way to "defeat" the compiler and get access to private data and
break data hiding. For instance, in C++ you can often do something like
#define private public
and in Java you can use reflection. The creator of Python, Guido van
Rossum, understands that sometimes there *are* good uses for breaking
data hiding (usually for testing and debugging). Because Python is an
interpreter where most features are done at runtime rather than compile
time, implementing data hiding in Python would hurt performance, and
there would be some way to break it anyway.
So why bother?
Instead, Python is "for consenting adults". Data hiding is very simple:
the developer flags objects they want to keep private with a leading
and that tells you that this is private and you shouldn't touch it. If
you decide to ignore this and touch it anyway, then:
- either you have a good reason, and that's okay;
- or you are a "consenting adult", and if your code blows up,
well, that's your own fault and don't complain to us.
More information about the Tutor