Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 502
Paul Avatar asked Jul 28 '11 15:07

Paul


People also ask

Can you import into a class Python?

Python modules can get access to code from another module by importing the file/function using import.

Can we import modules inside function in Python?

Importing inside a function will effectively import the module once.. the first time the function is run. It ought to import just as fast whether you import it at the top, or when the function is run.

How do you import modules in Python?

Importing Modules To make use of the functions in a module, you'll need to import the module with an import statement. An import statement is made up of the import keyword along with the name of the module. In a Python file, this will be declared at the top of the code, under any shebang lines or general comments.


1 Answers

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__.

like image 63
agf Avatar answered Sep 17 '22 15:09

agf