devoured elysium
devoured elysium

Reputation: 105027

Constants in python?

I have the following variables declared in a lot of functions, as I need those values in each one of them. Is there anyway I can declare them at a global scope or something, such as I won't have to declare them in all my methods? I am using all this methods on instance methods of a class of mine.

x = 0
y = 1
t = 2

In c# I'd just declare them as global class variables, but the problem is that I don't want to have to use them always as self.x, self.y and self.z, as it gets my algorithm's code uglier than it already is. How would you do this?

A typical usage of this would be:

def _GetStateFromAction(self, state, action):
    x = 0
    y = 1
    t = 2

    if (action == 0):
        return (state[x], state[y] - 1, state[t])

    if (action == 1):
        return (state[x] - 1, state[y], state[t])

Upvotes: 3

Views: 1138

Answers (6)

Andrew Jaffe
Andrew Jaffe

Reputation: 27077

If they're all within a single module, then they only live in that module's namespace and you don't have to worry about name clashes. (And you can still import them into other namesapaces)

For example

MyModWithContstants.py

x = 0
y = 0

def someFunc():
  dosomethingwithconstants(x,y)

and we can also do

anotherMod.py

from MyModWithConstants import x
# and also we can do
import MyModWithConstants as MMWC

def somOtherFunc():
  dosomethingNew(x, MMWC.y)  
  ## x and MMWC.y both refer to things in the other file

Upvotes: 12

Ryan Ginstrom
Ryan Ginstrom

Reputation: 14121

In addition to the separate module trick, if I want them in the same module I'll often put them in a class, like this:

class PathConstants(object):
    CSIDL_DESKTOP = 0
    CSIDL_PROGRAMS = 2

def get_desktop():
    return _get_path_buf(PathConstants.CSIDL_DESKTOP)

If you want to make them more constant-y, then you can make setattr throw:

class ConstantExeption(Exception):
    pass

class ProgramConstants(object):
    foo = 10
    bar = 13
    def __setattr__(self, key, val):
        raise ConstantExeption("Cannot change value of %s" % key)

# got to use an instance...
constants = ProgramConstants()
print constants.foo
constants.bar = "spam"

The traceback:

10
Traceback (most recent call last):
  File "...", line 14, in <module>
    constants.bar = "spam"
  File "...", line 9, in __setattr__
    raise ConstantExeption("Cannot change value of %s" % key)
__main__.ConstantExeption: Cannot change value of bar

Upvotes: 5

Thomas Ahle
Thomas Ahle

Reputation: 31594

import __builtin__
__builtin__.__dict__["X"] = 5

This will store the X constant in all modules executed until the interpreter exits.

Remember though to use it with care, as other python developers are not likely to expect this. I use it mainly for storing the translation function '_'.

Upvotes: -1

kriss
kriss

Reputation: 24157

If these "variables" are truly constants declaring them at module level seems logical. If you have to modify them from inside a function you just have to declare them global in that function.

Upvotes: 1

inspectorG4dget
inspectorG4dget

Reputation: 113905

Have you considered

global x, y, z
x=0
y=1
z=2

?

Upvotes: 0

Ben James
Ben James

Reputation: 125119

You could simply declare these variables at the module level (i.e. the top level of the .py source file) and there will be no need to use self or anything like that. In that case I think the convention would be to give them uppercase names.

By the way, I can't help but point out that you could be declaring them like this:

x, y, t = 0, 1, 2

Upvotes: 1

Related Questions