Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to prevent python module from being imported in another script

I need to avoid certain file to be imported elsewhere in a project.

From Preventing Python code from importing certain modules?, I have learned that

# myscript.py
import sys
sys.modules['mymodule']=None

will make any further

import mymodule

fail when the containing myscript.py is called.

However, in my use case I need to prevent mymodule from being imported in another script, by modifying only mymodule without adding anything to myscript.py

like image 933
00__00__00 Avatar asked Sep 09 '26 13:09

00__00__00


1 Answers

If I understood the question correctly, put this line at the beginning of your module:

#mymodule.py
if __name__!="__main__": raise ImportError("This module is not meant to be imported")
like image 191
Ahmed Ouerfelli Avatar answered Sep 11 '26 02:09

Ahmed Ouerfelli