Python imports a module in only one class

I am trying to get a module to import, but only if an object of a certain class is called. For instance:

class One(object):
    try:
        import OneHelper
    except ImportError:
        pass
    def __init__(self):
        # this function doesn't use OneHelper
        ...

    def blah(self):
        # this function does
        OneHelper.blah()

This is called NameError: global name 'OneHelper' is not definedwhen the function is called One.blah(). So far, the only thing I've found that works is to import the module into the actual functions that use it. So:

class One(object):
    def __init__(self):
        # this function doesn't use OneHelper
        ...

    def blah(self):
        try:
            import OneHelper
        except ImportError:
            pass
        # this function does
        OneHelper.blah()

But I do not want to import the module into every function in which I want to use it, I want it to be available for the whole class, but only if an instance of this class is created. Sorry if I am not clear enough ...

+5
source share
3 answers

import OneHelper , . dir(One) - OneHelper. One.OneHelper . , , self.OneHelper . ( One.OneHelper.)

+8

__init__ :

class One(object):
    def __init__(self):
        try:
            import OneHelper
        except ImportError:
            self.OneHelper = None
        else:
            self.OneHelper = OneHelper
    def blah(self):
        if self.OneHelper:
            self.OneHelper.blah()

, , , ?

+2

You can also use global OneHelperbefore importing the module. This adds OneHelper to the global namespace.

0
source

All Articles