Using a Python global variable

I'm a bit of a Python coding beginner, which has a slight impact on Java. The question I have right now is about using global variables in Python for constants and the like. In Java, we 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 a value at runtime:

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

      

The point is that in the latter case, after setting a static variable, it remains set. However, this is not the case in Python. If I create a global variable and then assign it in a function, that variable will only have an 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 way to do this, or are there any consequences and side effects that I am not aware of?

+3


source to share


1 answer


There is no constant variable per se 'definition in Python due to its dynamic nature. Constants are dictated by style and thus quoted from PEP 8

Constants are usually defined at the 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 a constant, define it at the module level, name it in uppercase, separated by an underscore, and follow the convention, so there are no other variables in any other scope that conflicts with the constant variable. You don't need a global classifier anyway, since a variable defined at the module level will be in scope at the function level anyway.



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']

      

+6


source







All Articles