Reputation: 183
I import a part of module instead of whole point because I am interested in accelerating my script.
I have the file called theFile.py
def goza():
print vari
funct()
vari = "called variable"
def funct():
print "CALLED FUNCTION"
something_else = 12
I if in my main:
from theFile import goza
And then run goza() It really has variable vari and function fuct. It means that if I import:
from theFile import goza
It actually import the whole module? But the only variable that is easy accessed is goza? How can import only part of the code as I expected? (that if I do something like from theFile import goza and use goza, that will be an error says there is no variable vari and function funct).
Thank you very much!
Upvotes: 2
Views: 116
Reputation: 348
Python will always execute the whole file at import time, and then those variables in module scope at the end of the execution are importable.
If there are parts of your module which you'd like to only execute when it's run as a script but not at import time then the idiom is to use:
def main():
code_here
if __name__ == "__main__":
main()
i.e.
def goza():
print vari
funct()
def main():
vari = "called variable"
def funct():
print "CALLED FUNCTION"
something_else = 12
if __name__ == "__main__":
main()
see http://docs.python.org/2/library/main.html
Upvotes: 2
Reputation: 137527
Don't worry about it.
I'm almost positive the entire module is compiled to bytecode and then read into memory, regardless. The different import
statements only have to do with which classes/functions/variables are brought into the global scope.
So basically you're worrying about nothing. This should have absolutely zero impact on the performance of your script. Spend your time looking for improvements elsewhere.
Upvotes: 2