Skip to content
Browse files

version 0.6: boolean and expression dealt with in cast

  • Loading branch information...
1 parent f3141ae commit c3ad17a09da1c7bceab591d2a50d3db2813a53c9 @3kwa committed Nov 15, 2012
Showing with 30 additions and 3 deletions.
  1. +10 −1 README.rst
  2. +2 −0 constants.ini
  3. +5 −1 constants.py
  4. +1 −1 setup.py
  5. +12 −0 test_constants.py
View
11 README.rst
@@ -36,6 +36,8 @@ unless specifically overridden in a section.
[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.
@@ -83,12 +85,19 @@ 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 pertinent.
+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)
View
2 constants.ini
@@ -6,3 +6,5 @@ a_string = 0350
[a_section]
something = a_section_value
just_for_me = 5.0
+flag = False
+minutes = 365 * 24 * 60
View
6 constants.py
@@ -109,7 +109,7 @@ def __getattr__(self, item):
@debug
def cast(constant):
"""
- cast string to int, float or keep as string
+ cast string to int, float, eval or keep as string
"""
if hasattr(constant, 'startswith') and constant.startswith('0') \
and '.' not in constant:
@@ -122,6 +122,10 @@ def cast(constant):
return float(constant)
except ValueError:
pass
+ try:
+ return eval(constant)
+ except (NameError, SyntaxError):
+ pass
return constant
@debug
View
2 setup.py
@@ -3,7 +3,7 @@
setup(
name='constants',
- version='0.5.0',
+ version='0.6.0',
description='The simple way to deal with environment constants.',
long_description=open('README.rst').read(),
author='Eugene Van den Bulke',
View
12 test_constants.py
@@ -25,3 +25,15 @@ def test_string_cast(self):
def test_integer_with_leading_zero_not_cast(self):
result = constants.Constants.cast('0350')
self.assertEqual('0350', result)
+
+ def test_boolean(self):
+ result = constants.Constants.cast('True')
+ self.assertEqual(True, result)
+
+ def test_expression(self):
+ result = constants.Constants.cast('365 * 24 * 60')
+ self.assertEqual(525600, result)
+
+ def test_invalid_expression(self):
+ result = constants.Constants.cast('3 * 5 / 100 %')
+ self.assertEqual('3 * 5 / 100 %', result)

0 comments on commit c3ad17a

Please sign in to comment.
Something went wrong with that request. Please try again.