conditional import into global namespace

mk mrkafk at gmail.com
Tue Mar 2 12:46:22 EST 2010


Hello everyone,

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




More information about the Python-list mailing list