Search code examples
pythonmodulepython-module

How do variables inside python modules work?


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?


Solution

  • 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)