constants


Nameconstants JSON
Version 2023.2.0 PyPI version JSON
download
home_pagehttp://github.com/3kwa/constants
SummaryThe simple way to deal with environment constants.
upload_time2023-02-21 00:07:37
maintainer
docs_urlNone
authorEugene Van den Bulke
requires_python
licenseBSD
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            =========
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_string = 0350

    [a_section]
    something = a_section_value
    just_for_me = 5.0
    flag = False
    minutes = 365 * 24 * 60

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:

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, float or boolean when pertinent.

>>> consts['all']
1
>>> consts.a_string
'0350'
>>> consts.flag
False

Expressions are evaluated.

>>> consts.minutes
525600

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

>>> consts.all
1

.. _Warning:

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 +ELLIPSIS
INFO constants.load
variable: __CONSTANTS__,
filename: constants.ini,
environment: a_section,
constants: {...}

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_.

.. _app_constants: https://github.com/leonardoborges/app_constants
.. _configparser: http://docs.python.org/library/configparser.html
.. _PyPI: http://pypi.python.org/pypi/constants
.. _GitHub: https://github.com/3kwa/constants
.. _suggestion: https://twitter.com/mw44118/status/256022281409658881
.. _warnings: http://docs.python.org/library/warnings.html
.. _logging: http://docs.python.org/library/logging.html

            

Raw data

            {
    "_id": null,
    "home_page": "http://github.com/3kwa/constants",
    "name": "constants",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Eugene Van den Bulke",
    "author_email": "eugene.vandenbulke@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/72/fa/f30ceeadac002c32ba72e87157293c7c1faeb5c3d2ad245365061c464134/constants-2023.2.0.tar.gz",
    "platform": null,
    "description": "=========\nconstants\n=========\n\n\nThe problem?\n============\n\nMost applications use constants. Many constants take different values based\non the environment the application is executed in.\n\nThink database credentials over development, testing, staging, production or\nstock market execution over development, testing, paper, production ...\n\n\nA solution\n==========\n\nShamelessly inspired by the app_constants_ gem, ``constants`` aims to solve that\nproblem (and that problem only).\n\n.ini file\n---------\n\n``constants`` uses the .ini file format to specify the application constants\nvalues in each environment. DEFAULT values are available in every environment\nunless specifically overridden in a section.\n\n::\n\n    [DEFAULT]\n    something = a_default_value\n    all =  1\n    a_string = 0350\n\n    [a_section]\n    something = a_section_value\n    just_for_me = 5.0\n    flag = False\n    minutes = 365 * 24 * 60\n\nTo find out more about ini files and sections, check the Python standard\nlibrary configparser_ documention.\n\nThe default file is ``constants.ini`` in the current working directory. but\nyou can use any filename you want cf. Instantiation_.\n\nEnvironment\n-----------\n\nDefine the environment the application will run in. The default environment\nvariable to store that value is __CONSTANTS__, but you can use any variable\nname you want cf. Instantiation_.\n\nMost platform have a way to do that, in bash:\n\n::\n\n    export __CONSTANTS__=a_section\n\n.. _Instantiation:\n\nInstantiation\n-------------\n\n>>> import constants\n>>> consts = constants.Constants()\n\nOn instantiation, constants looks for an environement variable named\n__CONSTANTS__ whose value is used to find out which section of the\nconstants.ini file should be used.\n\nConstants' constructor takes two (2) optional parameters. ``variable``\nlet's you specify the name of the environment variable and ``filename``\nthe absolute path to the .ini file containing the constants definitions.\n\n>>> consts = Constants(variable='AN_ENVIRONMENT_VARIABLE',\n...                    filename='constants.cfg') # doctest: +SKIP\n\nValues\n------\n\nTo access the values, the instance can be used like a dictionary (getitem).\n\n>>> consts['something']\n'a_section_value'\n\nValues are cast into integer, float or boolean when pertinent.\n\n>>> consts['all']\n1\n>>> consts.a_string\n'0350'\n>>> consts.flag\nFalse\n\nExpressions are evaluated.\n\n>>> consts.minutes\n525600\n\nValues can also be accessed using the . operator (getattr)\n\n>>> consts.all\n1\n\n.. _Warning:\n\nWarning\n-------\n\n\"We are responsible adults\" yet, inspired by Matthew Wilson's suggestion_ to\nraise an exception when an attempt is made to *change a constant*, ``constants``\nissues warnings_ ...\n\n>>> import warnings\n\n>>> with warnings.catch_warnings(record=True) as warning:\n...     # reassigning the constant all\n...     consts.all = 2\n\n>>> warning[0].message\nUserWarning('all changed to 2',)\n\n... and *changes the constant* anyway.\n\n>>> consts.all\n2\n\nIt does so with the dict like assignment as well.\n\n>>> with warnings.catch_warnings(record=True) as warning:\n...     consts['something'] = 'a_new_value'\n\n>>> warning[0].message\nUserWarning('something changed to a_new_value',)\n\n>>> consts['something']\n'a_new_value'\n\nLogging\n-------\n\n``constants`` aims to be a good logging_ citizen, grafting a logger to the\nlogging tree.\n\nAll calls to the logger methods expose an extra logRecord key called ``method``.\n\nWith the logging level set to INFO, it logs one and only one useful message.\n\n>>> import sys\n>>> import logging\n>>> logging.basicConfig(level=logging.INFO,\n...                     stream=sys.stdout,\n...                     format='%(levelname)s %(name)s.%(method)s %(message)s')\n>>> consts = constants.Constants() # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS\nINFO constants.load\nvariable: __CONSTANTS__,\nfilename: constants.ini,\nenvironment: a_section,\nconstants: {...}\n\nAt DEBUG level it becomes a tad *noisier*.\n\n>>> logging.root.setLevel(logging.DEBUG)\n>>> debug_me  = consts.just_for_me # doctest: +ELLIPSIS\nDEBUG constants.__getattr__ begin (..., 'just_for_me') {}\nDEBUG constants.__getitem__ begin (..., 'just_for_me') {}\nDEBUG constants.cast begin ('5.0',) {}\nDEBUG constants.cast end 5.0\nDEBUG constants.__getitem__ end 5.0\nDEBUG constants.__getattr__ end 5.0\n\nInstallation\n============\n\n``constants`` is available on PyPI_ ...\n\n::\n\n    pip install constants\n\n... and can be forked on GitHub_.\n\n.. _app_constants: https://github.com/leonardoborges/app_constants\n.. _configparser: http://docs.python.org/library/configparser.html\n.. _PyPI: http://pypi.python.org/pypi/constants\n.. _GitHub: https://github.com/3kwa/constants\n.. _suggestion: https://twitter.com/mw44118/status/256022281409658881\n.. _warnings: http://docs.python.org/library/warnings.html\n.. _logging: http://docs.python.org/library/logging.html\n",
    "bugtrack_url": null,
    "license": "BSD",
    "summary": "The simple way to deal with environment constants.",
    "version": "2023.2.0",
    "project_urls": {
        "Homepage": "http://github.com/3kwa/constants"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "72faf30ceeadac002c32ba72e87157293c7c1faeb5c3d2ad245365061c464134",
                "md5": "6d292f2f04feda992a31def0ad4328ff",
                "sha256": "c48048e3baa02803a0b4c31633c72bb9b2a029b025c76d552661f855e41ab86c"
            },
            "downloads": -1,
            "filename": "constants-2023.2.0.tar.gz",
            "has_sig": false,
            "md5_digest": "6d292f2f04feda992a31def0ad4328ff",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 5396,
            "upload_time": "2023-02-21T00:07:37",
            "upload_time_iso_8601": "2023-02-21T00:07:37.029677Z",
            "url": "https://files.pythonhosted.org/packages/72/fa/f30ceeadac002c32ba72e87157293c7c1faeb5c3d2ad245365061c464134/constants-2023.2.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-02-21 00:07:37",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "3kwa",
    "github_project": "constants",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "tox": true,
    "lcname": "constants"
}
        
Elapsed time: 0.34955s