Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python global variable usage

Tags:

python

I'm a bit of a beginner to coding in Python, which is a bit of a jump for me coming from Java. The question I have right now is about the use of global variables in Python for constants and such. In Java, we sort of have two ideas for constants, we can have something like this:

private static final HOME_URL_CONST = "localhost:8080";

Or if we need to assign the value at runtime:

private static HOME_URL = "";
public void init(){ 
  HOME_URL = "localhost:8080"; 
}

The point is that in the latter case, once you set the static variable, it stays set. However in Python, this is not the case. If I create a global variable and then assign it in a function, that variable will only have the assigned value inside that function. Right now i have something like this:

def initialize():
  global HOME_URL
  with open("urls.txt", 'rb') as f:
    HOME_URL = json.load(f.read())['urls']

is this an acceptable method of doing this or are there some repercussions and side effects I'm not aware of?

like image 782
Jainathan Leung Avatar asked Jan 21 '13 18:01

Jainathan Leung


1 Answers

In Python, there is no definition of const variable per se', because of its dynamic nature. Constants are dictated through Style and thus quoting from PEP 8

Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.

So, if you want a variable to be used as constant, define it at module level, name it with uppercase separated by underscore and follow the convention, so that there are no other variables in any other scope that conflicts with the constant variable. In any case you will not need any global qualifier, as a variable defined at module level would in any case would be in scope at the function level.

So in this particular case

HOME_URL = "localhost:8080"
def initialize():
      #global HOME_URL #You don't need this
      home_url = HOME_URL
      with open("urls.txt", 'rb') as f:
           #Constants are not supposed to mutate
           home_url = json.load(f.read())['urls']
like image 56
Abhijit Avatar answered Sep 30 '22 19:09

Abhijit