Reputation: 429
I usually need to import one or more identical modules to different py files, say
a.py
import sys
import os
b.py
import sys
c.py
import os
I don't want to import the same module again in different files, so I decide to write a importHelper.py and write the following
import sys
import os
So I just add import importHelper.py to a,b,c.py but outcome it does not work. (Cannot load the sys and os methods)
Is there any advice on how to import common modules on different files?
Thanks all for the reply.
Upvotes: 2
Views: 205
Reputation: 394995
Don't do that. Unnecessarily importing code into every module will get you to premature bloat. And from the Python Style Guide:
Wildcard imports (from import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools.
As furas points out, modules are only imported once per session anyways (although you might reload one.)
And as Eric Urban says, it is convention, and expected. If you share your work with others, you will frustrate them to no end if you do this.
Upvotes: 2
Reputation: 142641
Python imports module only once even if you import that module in many files. It remeber modules imported before. So you can import as many times as you wish.
You should add import module
in files which use that module to make code more readable for others (and for you).
Upvotes: 1
Reputation: 17871
It is possible with from importHelper import *
. In this case you can use the same syntax, i.e. sys.exit()
etc.
When you import it as import importHelper
, you'll have to use it as importHelper.sys.exit()
.
All in all, imported modules are merely labels (variable names) and can be used as such.
Upvotes: 2
Reputation: 3820
You should import the dependency in all files that need it. That is the python way.
Upvotes: 1