(python) Should my variable be local or global? (best practice)

When declaring a constant that uses only one function, should this variable be declared locally, because it is used only by this function, or globally, since it will never change?

IE, which is better:

CONSTANT = (1, 3, 5, 8)

##SOME OTHER CODE HERE

def function1(arg):
    if arg in CONSTANT:
        do something

or

def function1(arg):
    CONSTANT = (1, 3, 5, 8)
    if arg in CONSTANT:
        do something

I know that there are not many differences between the two, but I just wanted to know which of the two practices is preferable, as I am just starting out and want to create good habits.

+5
source share
3 answers

. , , , . , , , , . , .

+3

, :

  • Python , , .
  • , , .
  • .

, - , .

+1

, .

, . , , .

, . , - , , .

:

  • , ,
  • ,
  • .

In conclusion, I would say: do what you think is best, but try to encapsulate things as much as possible, where they belong (local people prefer global ones).

0
source

All Articles