0

I am asking about module privates, not class privates.

Suggested in here, a module private starts with one underscore, such a element is not copied along when using the from <module_name> import * form of the import command; it is however imported if using the import <moudule_name> syntax.

So the question is if I have to use import <moudule_name> syntax, how to avoid importing module private functions?

John
  • 331
  • 2
  • 11
  • 2
    Just don't access `module_name._private` members. The `_private` definitions will be executed regardless of whether you import them or not, so there's not any particular benefit to not importing them, just so long as you don't touch them. – Samwise May 24 '22 at 03:03
  • You cannot prevent users from using it. @Samwise – John May 24 '22 at 03:06
  • What, exactly, are you trying to avoid? You can *never* prevent users from using it. Python doesn't have access modifiers, and having a single underscore is all that is required conventionally. – juanpa.arrivillaga May 24 '22 at 03:14
  • @juanpa.arrivillaga I guess we can make it [harder](https://tio.run/##hVBLDoMgEN1ziukKSUwT7aYx6VmMH6gkCEShxtNTVNpareks5/1mnh5No@Tlqjs3cNOA0lRGuB1bVVtBz3rEMeABEyh6YBkCP7rj0kQYY1RTBj01VkckQzM2bTz@KAzNmZWV4UpOIIQJ2kA5YbLI7kKVhQBtS8GrtzBP4t0qXeVs2b@CZg4kPmiFbM47tkyPLdM/lqEX35FYOkK@sRgYF/TGiOOtVp2BV9EIfSrfv3UMpl/g7gznng) to access, though. – Kelly Bundy May 24 '22 at 03:21
  • And maybe the private function could also inspect who's calling it and throw a tantrum if's an outsider. – Kelly Bundy May 24 '22 at 03:26
  • @juanpa.arrivillaga, i am looking for a way, if possible, to programmatically avoid importing module private functions. If there is no such way, I will use documentation to address what Samwise suggested. – John May 24 '22 at 05:20

1 Answers1

0

A feasible way is to create a separate folder for the module, add __init__.py file and import all the contents of the module.

We assume that the original structure is as follows:

.
├── module_a.py
└── test_module_a.py

Modify it to:

.
├── module_a
│   ├── __init__.py
│   └── _module_a.py
└── test_module_a.py

The __init__.py file only imports the contents of the module a file using the asterisk syntax:

# module_a/__init__.py
from ._module_a import *

So when you are importing the module_a, the private function will not be visible because it has not been imported by the __init__.py file.

Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31
  • You meant storing all private functions in _module_a.py and adding a leading underscore for each of them? – John May 24 '22 at 03:11
  • @John No, the file content does not need to be modified. I modify the file name just to remind the user that it is protected. – Mechanic Pig May 24 '22 at 03:14