-3

How do I keep the following constant and true? (In other words globals?)

  UP    ::  Direction
DOWN    ::  Direction
LEFT    ::  Direction
RIGHT   ::  Direction
dirs =  [UP,    DOWN,   LEFT,   RIGHT]

My attempt:

#global definitions
UP = True
DOWN = True
LEFT = True
RIGHT = True
dirs = [UP, DOWN, LEFT, RIGHT]
Vincent Luc
  • 79
  • 1
  • 1
  • 5
  • 3
    What's wrong with that? Just don't ever reassign them. – Morgan Thrapp Jul 20 '15 at 19:37
  • 1
    *"constant and true"* isn't necessarily the same thing as *"globals"* - you can (but generally shouldn't) have global variables, and can definitely have local "constants". However, Python doesn't really have constants, all names can be reassigned. What are you actually trying to *do*? – jonrsharpe Jul 20 '15 at 19:39

2 Answers2

3

In Python there are no true constants. The closest thing you can do is create a variable and never reassign it. Your attempt looks like it will work fine.

One thing to note is that "constant and true" does not mean "global". The distinguishing feature of a global variable has nothing to do with constancy, but the scope at which the object can be referenced (namely, all). You can have global variables that aren't constant (in languages that allow constants, of course), and constant variables that are not global.

sschilli
  • 2,021
  • 1
  • 13
  • 33
0

I don't really know what you try to achieve, and from what you want to protect the value of the "constants" but one possible solution to create a numpy memmap array, assign a value to it and "open" it again as read only.

Geeocode
  • 5,705
  • 3
  • 20
  • 34