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?

6
  • 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. Commented May 24, 2022 at 3:03
  • You cannot prevent users from using it. @Samwise Commented May 24, 2022 at 3: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. Commented May 24, 2022 at 3:14
  • @juanpa.arrivillaga I guess we can make it harder to access, though. Commented May 24, 2022 at 3:21
  • And maybe the private function could also inspect who's calling it and throw a tantrum if's an outsider. Commented May 24, 2022 at 3:26

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You meant storing all private functions in _module_a.py and adding a leading underscore for each of them?
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.