0

I am currently creating a package for python but I would like to give access to the user only a specific set of functions defined in this package. Let's say that the structure file is as follows:

my_package/
    __init__.py
    modules/
        __init__.py
        functions.py

In functions.py, there are several functions as below (those are silly examples):

def myfunction(x):
    return my_subfunction1(x) + my_subfunction2(x)

def my_subfunction1(x):
    return x

def my_subfunction2(x):
    return 2*x

I want the user to be able to import my_package and directly access myfunction, but NOT my_subfunction1 and my_subfunction2. For example, let's say that only myfunction is useful for the user, whereas the sub-functions are only intermediate computations.

import my_package
a=my_package.myfunction(1) #should return 3
b=my_package.my_subfunction1(1) # should returns an error, function does not exist

I can think of two ways of solving my problem by adding the following lines to the __init__.py file inside my_package/

1/ from modules.functions import myfunction

2/ from modules.functions import *, and renaming the subfunctions with a leading underscore to exclude them from the starred import, ie :

_my_subfunction1 and _my_subfunction2

and both of these tricks seems to work well so far.

My question is thus : Is this the correct "pythonic" way to do ? Which one is better ? If none of them is the good way, how should I re-write it ?

Thanks for your help.

ldocao
  • 129
  • 2
  • 12
  • Possible duplicate to http://stackoverflow.com/questions/23151400/how-do-i-write-module-private-protected-methods-in-python – pmod Mar 10 '15 at 09:07
  • not exactly what I was looking for, but the thread you mentionned is a good complement to the answer below. – ldocao Mar 11 '15 at 01:55

1 Answers1

1

I believe you should take a look at the __all__ variable.

In your case, just set, in yout __init__.py:

__all__ = ['myfunction']
Francis Colas
  • 3,459
  • 2
  • 26
  • 31