Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: 'Private' module in a package

I have a package mypack with modules mod_a and mod_b in it. I intend the package itself and mod_a to be imported freely:

import mypack import mypack.mod_a 

However, I'd like to keep mod_b for the exclusive use of mypack. That's because it exists merely to organize the latter's internal code.

My first question is, is it an accepted practice in Python programming to have 'private' modules like this?

If yes, my second question is, what is the best way to convey this intention to the client? Do I prefix the name with an underscore (i.e. _mod_b)? Or would it be a good idea to declare a sub-package private and place all such modules there?

like image 453
Frederick The Fool Avatar asked Aug 30 '10 16:08

Frederick The Fool


People also ask

How do I indicate a private module in Python?

Python allows for private class members with the double underscore prefix.

What is __ init __ py for?

The __init__.py file makes Python treat directories containing it as modules. Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.

Can you have private functions Python?

In Python, there is no existence of Private methods that cannot be accessed except inside a class. However, to define a private method prefix the member name with double underscore “__”.

What is __ all __?

Python __all__ is a variable that can be set in the __init__.py file of a package. The __all__ variable is a list of strings that defines those symbols that are imported when a program does.


2 Answers

I prefix private modules with an underscore to communicate the intent to the user. In your case, this would be mypack._mod_b

This is in the same spirit (but not completely analogous to) the PEP8 recommendation to name C-extension modules with a leading underscore when it’s wrapped by a Python module; i.e., _socket and socket.

like image 71
Jeremy Avatar answered Oct 17 '22 01:10

Jeremy


The solution I've settled on is to create a sub-package 'private' and place all the modules I wish to hide in there. This way they stay stowed away, leaving mypack's module list cleaner and easier to parse.

To me, this doesn't look unpythonic either.

like image 40
Frederick The Fool Avatar answered Oct 17 '22 01:10

Frederick The Fool