Skip to content
Advertisement

How to limit a Python module to expose specific parts

I just made a module in python but I don’t want people to do this:

import mymodule
mymodule.

and this then shows all methods and variables I added to the module. I just want them to see specified ones because I have many additional ones that are only for internal use.

Advertisement

Answer

If this is your module mymodule.py:

def expose_this():
    print('yes please')


def but_not_this():
    print('definitely not')

Importing it directly like this:

import mymodule

Gives a user access to mymodule.expose_this() and mymodule.but_not_this(), there’s no way to change that, although you could call but_not_this something like _but_not_this instead and many editors would at least warn a user that they are not supposed to access that.

However, the right way to do it would be to create a package. Put your module in a separate folder (called mymodule), and add an __init__.py with this:

from .mymodule import expose_this

Now, if someone imports your package using the same import statement as before, they only have access to mymodule.expose_this()

import mymodule

mymodule.expose_this()  # this works
mymodule.but_not_this()  # this causes an error

There’s a lot more to say about creating packages and how to add content, but there’s good documentation and tutorials for that out there.

Note: if someone knows the internal structure of your module, they can still access but_not_this() with this:

import mymodule

mymodule.mymodule.but_not_this()

But they’d have to really want to – making it impossible is hard and there’s really no point, since someone will be able to get at your code anyway, if they need to. But if you want to make the intent clear, you could rename mymodule.py to _mymodule.py and prefix the functions you don’t want exposed with a _ as well – this helps editors to reinforce your intentions with the user.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement