I have a class that is dependent on subprocess functionality. I would
like to make it self-contained in the sense that it would import
subprocess if it's not imported yet.
What is the best way to proceed with this?
I see a few possibilities:
1. do a class level import, like:
class TimeSync(object):
import subprocess
2. do an import in init, which is worse bc it's ran every time an
instance is created:
def __init__(self, shiftsec, ntpserver):
import subprocess
Both of those methods have disadvantage in this context, though: they
create 'subprocess' namespace in a class or instance, respectively.
Is there anyway to make it a global import?
Regards,
mk
Just import subprocess at the top of your module. If subprocess
hasn't been imported yet, it will be imported when your module is
loaded. If it's already been imported, your module will use the
cached version that's already been imported.
In other words, it sounds like Python already does what you want. You
don't need to do anything special.
--
Jerry
Oh, thanks!
Hmm it's different than dealing with packages I guess -- IIRC, in
packages only code in package's __init__.py was executed?
Regards,
mk
I don't understand this. But there is no difference regarding caching &
execution between packages and modules.
Importing a package will execute the __init__.py, yes. But only once. As
will importing modules execute them, but only once.
All subsequent imports will just return the created module-object.
Unless you import something under a new name! That is, you can alter the
sys.path and then import a package/module under a different name -
python won't detect that.
Simplest example ist this:
---- test.py ----
class Foo(object):
pass
if __name__ == "__main__":
import test # import ourselves
# this holds, because we have
# __main__.Foo and test.Foo
assert Foo is not test.Foo
---- test.py ----
However, unless you mess with python, this is none of your concern.
Diez