PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 24, 2022

[FIXED] How to limit a Python module to expose specific parts

 August 24, 2022     module, python, python-3.10, python-module     No comments   

Issue

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.


Solution

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.



Answered By - Grismar
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing