-2

May I know in a Python environment, which is compliant with PEP-8?

Imports before global variables:

import some_library
GLOBAL_VARIABLE = "something"

Or global variables before imports:

GLOBAL_VARIABLE = "something"
import some_library
TylerH
  • 20,799
  • 66
  • 75
  • 101
LHY
  • 39
  • 4

2 Answers2

5

PEP 8 says about imports:

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

so this

import some_library
GLOBAL_VARIABLE = "something"

is PEP-8 compliant, and this

GLOBAL_VARIABLE = "something"
import some_library

is not.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Daweo
  • 31,313
  • 3
  • 12
  • 25
-3

The standard is for the imports to come before the global variables. There are several advantages to this:

  1. If you import a file with a global of the same name, then the variable defined in the import will take priority.
  2. If you import a file with another global, you won't have to write it here.
  3. You can import a file of globals and isolate that complexity.

As mentioned in some other comments, using globals is not really the best practice in Python. You can read more about this here.

shn
  • 865
  • 5
  • 14