[Tutor] how import a module upon instantiation of a class?

Albert-Jan Roskam fomcl at yahoo.com
Sun Aug 31 22:17:09 CEST 2014


Hi,

I want to import a module upon instantiation (not definition) of a class. What is the best way to do this? In my case, I need the "icu" module in only one place/class of the program. If that class won't be used, I don't want to have an ImportError. Also, it might be nice to do the imports only when you actually need that functionality. It's probably not really PEP-compliant to put the imports somewhere else than at the top of the module, but I can live with that.


import some_nonbuiltin  # I don't want it here!


class KlassA(object):
    import some_nonbuiltin  # nope

    def __init__(self):
        some_nonbuiltin = __import__("some_nonbuiltin") # idem

        x = some_nonbuiltin.blah()


class KlassB(object):
    """some_nonbuiltin not needed here! """

    def __init__(self):
        pass

 
Regards,

Albert-Jan




~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 

fresh water system, and public health, what have the Romans ever done for us?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 


More information about the Tutor mailing list