I'm trying to delete the __pycache__
folder for importing modules and if I:
from sys import dont_write_bytecode
dont_write_bytecode = True
import folder.modulename as modulename
the folder still gets created, but if I import all the library as shown below:
import sys
sys.dont_write_bytecode = True
import folder.modulename as modulename
the folder it's not created.
Can someone explain why this happens and if it's possible to avoid importing the whole sys
library?
Yes. When you write from sys import dont_write_bytecode
, that creates a new name in your namespace and binds it to the same object as the one in sys
. When you write dont_write_bytecode = True
, you are binding a different boolean object to your name, replacing your old binding. It has absolutely no effect on the dont_write_bytecode
variable that is part of sys
.
However, to correct another misconception, using from sys import xxx
is NOT any more efficient than import sys
.
The import you have written is exactly equivalent to:
import sys
dont_write_bytecode = sys.dont_write_bytecode
del sys
The from sys import
construct always has to import the entire module.