How do variables inside python modules work?

65 views Asked by At

I am coming from a Java background with Static variables, and I am trying to create a list of commonly used strings in my python application. I understand there are no static variables in python so I have written a module as follows:

import os

APP_NAME = 'Window Logger'
APP_DATA_FOLDER_PATH = os.path.abspath(os.environ['APPDATA'])+'\\%s' % APP_NAME
CURRENT_SESSION_NAME = 'session_1'
CURRENT_SESSION_XML_PATH = APP_DATA_FOLDER_PATH + '\\%s%s' % (CURRENT_SESSION_NAME, '.xml')

is this an acceptable way to store strings in python?

3

There are 3 answers

0
user2314737 On BEST ANSWER

The convention is to declare constants in modules as variables written in upper-case (Python style guide: https://www.python.org/dev/peps/pep-0008/#global-variable-names).

But there's no way to prevent someone else to re-declare such a variable -- thus ignoring conventions -- when importing a module.

There are two ways of working around this when importing modules by from ... import *:

  • use a name that begins with an underscore for the constant that should't be exported
  • define a list __all__ of constants and functions that are supposed to be public (thus excluding all objects not contained in the __all__list)
0
aadarshsg On

You can separate the configuration from the program itself. Check out: http://wiki.python.org/moin/ConfigParserShootout

0
Alex Huszagh On

If you need to define a constant that is static, it should be done at the module level, with all capitals separated by underscores, as follows:

https://www.python.org/dev/peps/pep-0008/#constants

In short, yes, that's fine.

Pep8 has recommended styles and conventions for Python code that I highly recommend you follow.