user35288
user35288

Reputation:

Python import a module into one class only

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

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 causes a NameError: global name 'OneHelper' is not defined when the One.blah() function is called. So far the only thing I have found that works is importing 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 don't want to have to import the module in each function I want to use it in, I want it to be available to the whole class, but only if an instance of that class is instantiated. Apologies if I'm not being clear enough...

Upvotes: 5

Views: 8410

Answers (3)

kousha
kousha

Reputation: 782

You might also consider using global OneHelper before importing the module. This adds the OneHelper to the global namespace.

Upvotes: 0

kindall
kindall

Reputation: 184455

The import OneHelper works fine in the class, making it a class attribute. You can verify this with dir(One) after defining your class -- there's your OneHelper attribute. One.OneHelper is a reference to the module. In an instance, of course, you may access it as self.OneHelper from your methods. (You could also continue to access it as One.OneHelper.)

Upvotes: 7

Paulo Scardine
Paulo Scardine

Reputation: 77399

Import it on __init__ and attribute to some property:

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()

Your example looks funny because if the module fails to import what is the point of calling it later?

Upvotes: 2

Related Questions