0

I have a module in my code called a.py which looks a bit like this:

import sqlite3
from sqlite3 import *
"""The point of importing twice in a different way is to
have a.py imported by someone and have all the sqlite3 functions (with some overriden by a.py)
but a.py still needs access to the source sqlite3 functions that he overrides"""
def connect(database): #overriding sqlite3's connect()
    print "It worked!"
    return sqlite3.connect(database)

and a file called b.py:

import a
a.sqlite3.connect("data.db")

I want to make the code in b.py invalid as no one should be able access the original (non-overriden) functions through a.py, how can I do this?

Jim
  • 125
  • 1
  • 8
  • Do you mean that the name *sqlite3* should not be accessible through module *a*? In that case, have a look at this: http://stackoverflow.com/questions/44834/can-someone-explain-all-in-python. It's not exactly what you ask for, but it at least hides them in `from a import *`. – Ilja Everilä Jun 01 '16 at 08:16
  • Why would you *want* to do that? – jonrsharpe Jun 01 '16 at 08:17
  • @jonrsharpe In my project, the user can code in Python and can't access any modules but the modules I supply (which is necessary to me), everything works well but the only problem is that he can access the built-in modules (which I don't want him too) through my modules. – Jim Jun 01 '16 at 08:27
  • You realise that by saying *"which is necessary to me"* you fail to answer my question? **Why?** Python isn't designed for cases like this, *"we're all consenting adults here"*. Just document the interface they *should* be using. – jonrsharpe Jun 01 '16 at 08:42

2 Answers2

1

I'm afraid that you can't! Check here for more details: https://stackoverflow.com/a/1547163/1548838

But you still can use import sqlite3 as _sqlite3 and use it later like _sqlite3.connect. This will tell your module users (convention only) not to use this attribute.

And you still can use __all__ module variable as Ilja Everilä mentioned to prevent from a import *.

Community
  • 1
  • 1
Moamen
  • 706
  • 7
  • 19
0

What about this? Depending on the goal, it's sometimes possible to hide names inside functions / lambdas.

def connect(database): #overriding sqlite3's connect()
   import sqlite3
   print "It worked!"
   return sqlite3.connect(database)

But anyway, I don't think trying to hide modules in Python is reasonable.

honza_p
  • 2,073
  • 1
  • 23
  • 37