Python - most convenient way to define constant variables used just once

GriMel picture GriMel · Jan 11, 2016 · Viewed 12.3k times · Source

Let's say I have a file "icon.ico" and an url "url.com".
The'll be used just once within the class - "icon.ico" will be set to some window and we'll do the request to url in one method.
I have three ways to define these variables.

1-st way - define as global constants

#in the top of the file
ICON = "icon.ico"
URL = "http://url.com"

#and then
def setIcon(self):
    self.setWindowIcon(QtGui.QIcon(ICON))

def getData(self):
    content = requests.get(URL).content

2-nd way - define as variables of the class

def __init__(self):
    self.url = "http://url.com"
    self.icon = "icon.ico"

3-rd way - define just within the method the'll be used

def setIcon(self):
    icon = "icon.ico"

def getData(self):
    url = "http://url.com"

Answer

pposca picture pposca · Jan 11, 2016

Rules of thumb

  • In general, you should avoid global variables because they live in memory since you import the module until the program finishes (1st case)
  • In general, you should avoid to fix values inside a function (2nd and 3rd cases) because it makes the function les reusable.

Instead of:

def __init__(self):
    self.url = "http://url.com"
    self.icon = "icon.ico"

or

def setIcon(self):
    icon = "icon.ico"

is preferible:

def __init__(self, url, icon):
    self.url = url
    self.icon = icon

or, if you think the values are going to be 90% the same:

def __init__(self, url="http://url.com", icon="icon.ico"):
    self.url = url
    self.icon = icon

Tips of when to use each case

1-st way - define as global constants

  • The constant has sense as a module scope constant. Remember that several classes and functions may be declared inside the same module. This means the constant is going to be used along the whole module and it does not owns to any specific class.
  • You need to find the constant quickly, usually to change its value. In this case maybe you don't really need a constant, but a variable.

2-nd way - define as variables of the class

  • If it is a variable of the class, it is not a constant. If you want to use either a constant or a variable of the class (what is at class level and not at instance level), you should use the 4-th way - as a class level constant.
  • If you want an instance level constant or variable, you should use the 2dn rule of thumb

3-rd way - define just within the method the'll be used

  • You should avoid this way in favor of the 2nd rule of thumb

4-th way - as a class level constant

  • Recomendded way only for both variables and constants that share all the instance of the same class, what means, in fact, class level or class scope