How to structure a Python module to limit exported characters?

I am writing a Python module whose purpose is to export a single data structure. I believe that this means that my module should export one character (for example, foo ), while all other characters have an underscore with a prefix.

Creating a data structure requires enough code โ€” how should I structure a module to ensure that no characters in this code are exported without a prefix? Two approaches are possible:

  • Put the generation code at the top level, being careful when using underscores, for example:

     _bar = ... for _i in ...: _bar.append(...) foo = [_bar, ...] 
  • Put the generation code in a function that returns a data structure. To do this, only the function name must be used with an underscore. For instance:

     def _generate_foo(): bar = ... for i in ...: bar.append(...) return [bar, ...] foo = _generate_foo() 

Is any of these approaches considered better? Or is there any other way to structure this module that would be preferable?

+5
source share
2 answers

Note that using underscores only prevents the import of this name with from module import * (as documented ). It does not make the name "private" in any real way. People can still see everything in your module by doing import module and then module._hiddenStuff .

In your case, you should use __all__ . The code should be what you want, but at the top of the module:

 __all__ = ['foo'] # foo being the one thing you do want to export 

This has the same effect as underlining, but it is much better if you want to exclude most things and not include them.

+11
source

I prefer the function definition approach in terms of ease of maintenance.

It is also important to remember that we all agree with adults, and the responsibility for using your module in how it is best suited for users lies with the users.

However, the use of underscores is supported by PEP-8 , so any _characters will not be imported using import *

0
source

Source: https://habr.com/ru/post/1206468/


All Articles