2 ms·
Python doesn't have true encapsulation unless you drop down to the C level to enforce it separately from the actual runtime. Unofficially, there are conventions
by nonameiguess 6y ago
Python doesn't have true encapsulation unless you drop down to the C level to enforce it separately from the actual runtime. Unofficially, there are conventions on how to mark functions as part of a public interface, but practically speaking, if someone can import your library, they can do whatever they want with it, including adding and changing behavior at runtime. Classes, modules, and even class and function definitions are just hash tables under the hood, and you can change what a given symbol refers to in whatever arbitrary way you want to.
Granted, you shouldn't do very much of that except in some extremely specialized and careful circumstances, but in a language that makes it really easy, you have to be extremely disciplined and often delivery velocity takes precedence over careful planning of what really constitutes a public API.
Practically speaking, putting separate services in literally separate process spaces where the only way they can communicate is via message passing is the only way to really enforce encapsulation.
- nonameiguess 6y agoFor an example of what I mean, check out the https://pypi.org/project/aioify/ https://pypi.org/project/aioify/ library. This intercepts all of the function and method definitions in a module as they are being imported and rewrites them on the fly to turn all normal functions into async functions. The language designers definitely took the path of we're just going to assume you know what you're doing and give you absolutely every last foot of rope you could possibly want to hang yourself with. It does make things fast and easy. See all of the complaints here lately about having to rewrite significant parts of an application to become async as soon as any part of it becomes async? Not a problem in Python. There's a library to just automatically rewrite all code as it is being imported, at the cost that the code you're actually running is not the code you see in your repos.
- willcipriano 6y agoYou can kinda sorta make private variables in Python with some namespace abuse: def make_get_private(var): . . . .private_var = var . . . .def get_private(): . . . . . . . .return private_var . . . .return get_private get_private = make_get_private("spam") You can't readily modify private_var after it is set in this case, you could also make and return a set_private function as well. I imagine you could do a whole module like this and then have it create it's functions at runtime to produce this "private" namespace. It would be a mess though.