I have always been using this method:
from sys import argv
and use argv
with just argv. But there is a convention of using this:
import sys
and using the argv by sys.argv
The second method makes the code self documented and I (really) adhere to it. But the reason I prefer first method is it is fast because we are importing only the function that is needed rather than import the whole module (which contains more useless functions which python will waste time importing them). Note that I need just argv and all other functions from sys are useless to me.
So my questions are. Does the first method really makes the script fast? Which method is preferred most? Why?
Best Answer
Importing the module doesn't waste anything; the module is always fully imported (into the
sys.modules
mapping), so whether you useimport sys
orfrom sys import argv
makes no odds.The only difference between the two statements is what name is bound;
import sys
binds the namesys
to the module (sosys
->sys.modules['sys']
), whilefrom sys import argv
binds a different name,argv
, pointing straight at the attribute contained inside of the module (soargv
->sys.modules['sys'].argv
). The rest of thesys
module is still there, whether you use anything else from the module or not.There is also no performance difference between the two approaches. Yes,
sys.argv
has to look up two things; it has to look upsys
in your global namespace (finds the module), then look up the attributeargv
. And yes, by usingfrom sys import argv
you can skip the attribute lookup, since you already have a direct reference to the attribute. But theimport
statement still has to do that work, it looks up the same attribute when importing, and you'll only ever need to useargv
once. If you had to useargv
thousands of times in a loop, it could perhaps make a difference, but in this specific case it really does not.Hence, the choice between one or the other should be based solely on coding style.
In a large module, I'd certainly use
import sys
; code documentation matters, and usingsys.argv
somewhere in a large module makes it much clearer what you are referring to than justargv
ever would.If the only place you use
argv
is in a'__main__'
block to call amain()
function, by all means usefrom sys import argv
if you feel happier about that:I'd still use
import sys
there myself. All things being equal (and they are, exactly, in terms of performance and number of characters used to write it), that is just easier on the eye for me.If you are importing something else altogether, then perhaps performance comes into play. But only if you use a specific name in a module many times over, in a critical loop for example. But then creating a local name (within a function) is going to be faster still: