greenbeaf
greenbeaf

Reputation: 177

Is this correct to import module only in function, not in a start of file?

So, i have a itchy question about import ModuleName and where i should to put this operator. In a start of file or in a function?

import some_module

def main():
    some_module.SomeStuff()

Or:

def main():
    import some_module
    some_module.SomeStuff()

But if i'll use it in more than one function? Will this correct or stupid? Or i need to create class with __init__ function like this: self.module = some_module.SomeStuff()? And then call it in other functions under a class?

Upvotes: 0

Views: 1020

Answers (4)

BrutalGames
BrutalGames

Reputation: 1

Upvotes: 0

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

pep08 recommands that all imports should happen at the beginning of the module, and that's the way to go unless you have a very compelling reason to do otherwise.

The only reason I can think of would be a circular dependency between two modules (module A tries to import module B which tries to import module A etc...), but then it's better to cleanly solve the problem by factoring the common elements in a third module that depends neither on A nor B.

Upvotes: 0

Abhishta Gatya
Abhishta Gatya

Reputation: 923

The correct way is import module or from module import func_a in the start of the file. It will look cleaner and better. If you only want to import one or two functions just use the second one.

Upvotes: 0

metmirr
metmirr

Reputation: 4302

Creating a class for import is not pythonic actually it's bad. You should import module as a name space for calling functions in that module or you can import specific functions:

from some_module import SomeFunc1, SomeFunc2
# or
import some_module
some_module.SomeFunc1()

Import statement must be at top of the source file(look pep8)

Upvotes: 1

Related Questions