Paul
Paul

Reputation: 21975

Importing modules inside python class

I'm currently writing a class that needs os, stat and some others.

What's the best way to import these modules in my class?

I'm thinking about when others will use it, I want the 'dependency' modules to be already imported when the class is instantiated.

Now I'm importing them in my methods, but maybe there's a better solution.

Upvotes: 85

Views: 122748

Answers (4)

nvd
nvd

Reputation: 3371

import sys
from importlib import import_module

class Foo():

    def __init__(self):

       moduleName = "myLovelyModule"

        # If conditional importing is needed, a variable updated
        # from the configuration of the application can be used.
        self.importTheModule = True # "True" Or "False"

        self.importedModule = None

        if self.importTheModule:
            self.importedModule = import_module(moduleName)

        # ---
        # Usage:

        if self.importedModule is not None:
            self.importedModule.functionA(params)

        # or

        if moduleName in sys.modules:
            self.importedModule.functionA(params)

        # or

        if self.importTheModule:
            self.importedModule.functionA(params)
        # ---

Upvotes: 22

Constantinius
Constantinius

Reputation: 35039

This (search for the section "Imports") official paper states, that imports should normally be put in the top of your source file. I would abide to this rule, apart from special cases.

Upvotes: 1

agf
agf

Reputation: 176730

If your module will always import another module, always put it at the top as PEP 8 and the other answers indicate. Also, as @delnan mentions in a comment, sys, os, etc. are being used anyway, so it doesn't hurt to import them globally.

However, there is nothing wrong with conditional imports, if you really only need a module under certain runtime conditions.

If you only want to import them if the class is defined, like if the class is in an conditional block or another class or method, you can do something like this:

condition = True

if condition:
    class C(object):
        os = __import__('os')
        def __init__(self):
            print self.os.listdir

    C.os
    c = C()

If you only want it to be imported if the class is instantiated, do it in __new__ or __init__.

Upvotes: 58

user395760
user395760

Reputation:

PEP 8 on imports:

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

This makes it easy to see all modules used by the file at hand, and avoids having to replicate the import in several places when a module is used in more than one place. Everything else (e.g. function-/method-level imports) should be an absolute exception and needs to be justified well.

Upvotes: 16

Related Questions