0

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?

greenbeaf
  • 177
  • 1
  • 2
  • 9

4 Answers4

1

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)

metmirr
  • 4,234
  • 2
  • 21
  • 34
0
0

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.

Abhishta Gatya
  • 883
  • 2
  • 14
  • 32
0

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.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118