2

let's say that I have a python file for some task written in OOP. some classes in my code use libraries such as pandas, csv ... Is it ok to import these libraries just before the main() function? Technically it works but I'm not sure if this is the right way

class A
class B
class C


import csv
import pandas

def main ():
    #pass
if __name__ == '__main__':
main()
am fs
  • 51
  • 5
  • Maybe you should consider asking this question here: https://codereview.stackexchange.com/ – Newskooler Sep 13 '19 at 12:26
  • it's not about code because as i said it works ! but when u use classes that need libraries where do u import them? maybe in the head of the file maybe before main ..? – am fs Sep 13 '19 at 12:29
  • 1
    By convention, `import` lines are the 2nd thing in the file after an optional shebang (`#!/usr/bin/env python`) line. – silleknarf Sep 13 '19 at 12:29
  • even in an oop code? – am fs Sep 13 '19 at 12:30
  • Yes, see the section on imports as Mikah has linked below for more detail: https://www.python.org/dev/peps/pep-0008/#imports – silleknarf Sep 13 '19 at 12:32

1 Answers1

4

PEP8 specifically describes where imports should go. Best to follow that.

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

EDIT TO ADD: You asked about import placement when programming OOP code. Assuming you're referring to Object Oriented Programming, that is a design pattern and has no bearing on the proper placement of imports. Imports are kept at the top of the module file to make it easy for anyone to easily see what dependencies a module has.

So, even if - to use your example - classes A, B, and C don't use csv or pandas, you'd still put those at the top because the module uses them even if some specific classes don't.

meshtron
  • 1,110
  • 9
  • 19
  • thx but that's not what i asked for – am fs Sep 13 '19 at 12:33
  • 1
    Perhaps you should edit your question because it appears you're asking specifically where imports should go. I'm assuming (as I think others are) that OOP -> object oriented programming. If that's true, it has no bearing on the proper placement of imports. If that's not the case, please clarify. – meshtron Sep 13 '19 at 12:36
  • @MikahBarnett well, it seems to me that it is **exactly what you asked for**, so it is the right answer – nacho Sep 13 '19 at 12:51