Defining private module functions in python
In Python, a leading underscore _
designates a function as private, signifying it's meant for internal use inside a module.
This "privacy" isn't enshrined by Python, rather, it's a convention respected among programmers – a polite request to other developers saying, "Hey, do not touch this!"
Enforcing "privacy" in modules
While Python doesn't offer an explicit mechanism to enforce private use at the module level, it does provide strategies we can employ. Python incorporates name mangling for class methods (using double underscores) to obfuscate and implicitly protect data, but when it comes to module-level functions, it leaves the decision in our more than capable hands.
Here, the _for_my_eyes_only()
function may be used within the module it resides in, but the leading underscore suggests to other developers that it isn't intended for use outside of it.
A step deeper: Inner secrets
You can level-up the encapsulation within a function using what's called an inner function. Remember, Python loves you and gives you all the necessary tools... use them wisely!
Here, the _private_plan()
function lives comfy and cozy inside the public_function()
and is accessible only from there, providing another level of privacy.
No wildcards in imports, please!
Be explicitly explicit when it comes to imports. Remember, clearer code is happier code.
Avoid using from module import *
like your code's life depends on it (because greatly, it does!) Wildcard imports can pull in unexpected names, even those intending to be private. It's like aiming for a dartboard blindfolded - who knows what you'll hit?
Managing with classes
Class-level privacy employs double underscores (__
) to invoke name mangling and prevent their accidental misuse.
Remember, even here, we're not guaranteeing absolute privacy. The intention is to avoid clashes rather than prevent access.
Pythonic Privacy: Trust, not Enforcement
The essence of privacy in Python caters to the language's philosophy of giving the developers ample freedom. It's about respect: "Look, but don't touch!".
Was this article helpful?