Skip to main content

the simple way to deal with environment constants

Project description

The simple way to deal with environment constants!

The problem?

Most applications use constants. Many constants take different values based on the environment the application is executed in.

Think database credentials over development, testing, staging, production or stock market execution over development, testing, paper, production …

A solution

Shamelessly inspired by the app_constants gem, constants aims to solve that problem (and that problem only).

.ini file

constants uses the .ini file format to specify the application constants values in each environment. DEFAULT values are available in every environment unless specifically overridden in a section.

[DEFAULT]
something = a_default_value
all =  1

[a_section]
something = a_section_value
just_for_me = 5.0

To find out more about ini files and sections, check the Python standard library configparser documention.

The default file is constants.ini in the current working directory. but you can use any filename you want cf. Instantiation.

Environment

Define the environment the application will run in. The default environment variable to store that value is __CONSTANTS__, but you can use any variable name you want cf. Instantiation.

Most platform have a way to do that, in bash:

export __CONSTANTS__=a_section

Instantiation

>>> import constants
>>> consts = constants.Constants()

On instantiation, constants looks for an environement variable named __CONSTANTS__ whose value is used to find out which section of the constants.ini file should be used.

Constants’ constructor takes two (2) optional parameters. variable let’s you specify the name of the environment variable and filename the absolute path to the .ini file containing the constants definitions.

>>> consts = Constants(variable='AN_ENVIRONMENT_VARIABLE',
...                    filename='constants.cfg') # doctest: +SKIP

Values

To access the values, the instance can be used like a dictionary (getitem).

>>> consts['something']
'a_section_value'

Values are cast into integer or float when possible.

>>> consts['all']
1

Values can also be accessed using the . operator (getattr)

>>> consts.all
1

Warning

“We are responsible adults” yet, inspired by Matthew Wilson’s suggestion to raise an exception when an attempt is made to change a constant, constants issues warnings

>>> import warnings
>>> with warnings.catch_warnings(record=True) as warning:
...     # reassigning the constant all
...     consts.all = 2
>>> warning[0].message
UserWarning('all changed to 2',)

… and changes the constant anyway.

>>> consts.all
2

It does so with the dict like assignment as well.

>>> with warnings.catch_warnings(record=True) as warning:
...     consts['something'] = 'a_new_value'
>>> warning[0].message
UserWarning('something changed to a_new_value',)
>>> consts['something']
'a_new_value'

Logging

constants aims to be a good logging citizen, grafting a logger to the logging tree.

All calls to the logger methods expose an extra logRecord key called method.

With the logging level set to INFO, it logs one and only one useful message.

>>> import sys
>>> import logging
>>> logging.basicConfig(level=logging.INFO,
...                     stream=sys.stdout,
...                     format='%(levelname)s %(name)s.%(method)s %(message)s')
>>> consts = constants.Constants() # doctest: +NORMALIZE_WHITESPACE
INFO constants.load
variable: __CONSTANTS__,
filename: constants.ini,
environment: a_section,
constants: {'all': '1', 'just_for_me': '5.0', 'something': 'a_section_value'}

At DEBUG level it becomes a tad noisier.

>>> logging.root.setLevel(logging.DEBUG)
>>> debug_me  = consts.just_for_me # doctest: +ELLIPSIS
DEBUG constants.__getattr__ begin (..., 'just_for_me') {}
DEBUG constants.__getitem__ begin (..., 'just_for_me') {}
DEBUG constants.cast begin ('5.0',) {}
DEBUG constants.cast end 5.0
DEBUG constants.__getitem__ end 5.0
DEBUG constants.__getattr__ end 5.0

Installation

constants is available on PyPI

pip install constants

… and can be forked on GitHub.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

constants-0.3.0.tar.gz (3.9 kB view details)

Uploaded Source

File details

Details for the file constants-0.3.0.tar.gz.

File metadata

  • Download URL: constants-0.3.0.tar.gz
  • Upload date:
  • Size: 3.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for constants-0.3.0.tar.gz
Algorithm Hash digest
SHA256 e672b684404737f25a141e9d0e11f4b01ded2aaf4434031ea957422ec3fcfafb
MD5 08c4d8c4d9808b075b718e96bf8f1dda
BLAKE2b-256 1a0a17b2d9c5d8cd144da30487e6f4cb379a89a9613bd6072ba84ba884399f31

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page